指向c中链表的第一个元素

时间:2018-11-06 00:37:21

标签: c linked-list

我希望你能帮助我,这真的很重要。请 我有一个程序,需要使用链接列表逐个字符地打印23次字符的名称。我已经使它可以打印一次,即使我有一个for循环,我也无法使其打印23次。请帮忙。我不知道从哪里开始。

通过回答这个问题,您真的会对我有很大帮助,我已经做了很多尝试,但是我仍然不知道该怎么做。提前致谢。

#include <conio.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct L {
    char c;
    struct L *next;
}List;

List *l = NULL; // list head, we'll prepend nodes here
int c;          // variable for current read character

List *getInput(void)
{
    while ((c = getchar()) != '\n') {       // read until enter
        List *n = calloc(1, sizeof(List)); // create new list node
        n->c = c;     // store read character in that node
        n->next = l;  // prepend newly created node to our list
        l = n;        // store newly created node as head of list
    }
    return l;
}
int main ( void ) {
    printf("Ingresa tu nombre.\n");
    getInput();
    printf("\n");
    int i = 0;
    for(i;i<23;

        //I tried something like l=1; here bit it didn't work.

        while (l != NULL) { // while we have not reached end of list
            putchar(l->c);  // print character stored in list
            printf("\n");
            l = l->next;    // and advance to next list node
        }
    }

    return 0;
}

1 个答案:

答案 0 :(得分:3)

每次通过for循环,都需要从列表的开头开始。这意味着您不能覆盖指向列表开头的变量l。相反,请使用其他变量进行迭代。

int main ( void ) {
    printf("Ingresa tu nombre.\n");
    getInput();
    printf("\n");
    int i = 0;
    for(i;i<23;i++){
        List *cur = l;
        while (cur != NULL) { // while we have not reached end of list
            putchar(cur->c);  // print character stored in list
            printf("\n");
            cur = cur->next;    // and advance to next list node
        }
    }

    return 0;
}