读取字符串到链表

时间:2013-11-15 20:46:57

标签: c

我必须编写程序,将用户输入的字符串存储到链表中,然后反向打印 - 如果用户输入Hello。输出应该是.olleH。

我不太了解列表的全部内容,但是我提出了一些建议,非常感谢任何反馈。

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

List *getInput( void ) {
    List *t = calloc(1, sizeof(List));
    int i;
    for (i=0; getchar() != '.'; i++) {
        t->c = getchar();
        t->next = NULL;
        printf("%c", t->c);
        t = t->c;
        t->next = t->next->next;
    }
    return t;
}

int main ( void ) {
    getInput();
    return 0;
}

现在我只是尝试将它存储在列表t中,使用getchar()逐字符存储。然后我想用另一个打印它来循环计数。由于某些原因,它不起作用,而我(不完全理解列表的概念)无法弄清楚原因。

欣赏任何帮助家伙!

1 个答案:

答案 0 :(得分:1)

由于您要反向打印输入字符串,最简单的方法是以相反的顺序将字符串存储在链接列表中,即在将字符读取到列表的开头(“head”)时将字符前置。所以在开头列表中将为空,然后它将包含“H”,然后是“eH”,“leH”等等。这是samblo代码:

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

    while ((c = getchar()) != EOF) {       // read characters one by ine, until end-of-file
        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;
}

以下是打印列表的方法:

void printList (List *l)
{
    while (l != NULL) { // while we have not reached end of list
        putchar(l->c);  // print character stored in list
        l = l->next;    // and advance to next list node
    }
}
相关问题