簡體   English   中英

指向c中鏈表的第一個元素

[英]Point to first element of a linked list in c

希望您能幫助我,這非常重要。 請我有一個程序,我需要使用鏈接列表逐個字符打印一個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;
}

每次通過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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM