簡體   English   中英

打印鏈表結構C

[英]Printing linked list structure C

因此,最近我不得不創建一個鏈接列表結構,並且我想有一個創建它的功能(希望如此),但是現在我遇到了一個簡單的問題,那就是將其打印到控制台中。 我不知道我創建的結構是否有問題,還是打印有問題。 如果有人能找到我的代碼出了什么問題,我將不勝感激:

struct z { int a; struct z *next; };
struct z *head, *node, *next;
int data, x = 1;

int CreateList() {
    printf("Enter 0 to end\n");
    printf("Enter data no. %d: ", x);
    x++;
    scanf("%d", &data);
    if (data == 0) return 0;
    head = (struct z *)malloc(sizeof(struct z));
    if (head == NULL) { printf("Error creating head"); return 0; }
    node = head;
    node->a = data;
    node->next = NULL;
    while (data) {
        next = (struct z *)malloc(sizeof(struct z));
        if (next == NULL) { printf("Error creating next node no. %d", x); return 0;}
        node = next;
        printf("Enter data no. %d: ", x);
        x++;
        scanf("%d", &data);
        node->a = data;
        node->next = NULL;
    }
    return 0;
}


int main() {
    CreateList();
    node = head;
    while (node != NULL) {
        printf("%d ", node->a);
        node = node->next; //<=== crash on this line
    }
    return 0;
}

我的輸出始終只是第一個輸入的int,然后全部崩潰在標記的行上。

您的main循環使用了錯誤的變量:

int main(){
    CreateList();
    node = head;
    while (next != NULL) {
        printf("%d ", node->a);
        node = node->next; //<=== crash on this line
    }
    return 0;
}

您應該改為使用node

int main(){
    CreateList();
    node = head;
    while (node != NULL) {
        printf("%d ", node->a);
        node = node->next; //<=== crash on this line
    }
    return 0;
}

順便說一句, headnodenext應該是局部變量,並且head應該由CreateList()返回。

CreateList()實際上並未正確創建列表:節點在創建時未鏈接到列表,只有第一個節點存儲在head

這是返回列表和相應main功能的更正版本:

struct z { int a; struct z *next; };

struct z *CreateList(void) {
    struct z *head, *node, *next;
    int data, x = 1;

    printf("Enter 0 to end\n");
    printf("Enter data no. %d: ", x);
    x++;
    if (scanf("%d", &data) != 1 || data == 0)
        return NULL;
    head = malloc(sizeof(struct z));
    if (head == NULL) {
        printf("Error creating head");
        return NULL;
    }
    node = head;
    node->a = data;
    node->next = NULL;
    for (;;) {
        printf("Enter data no. %d: ", x);
        x++;
        if (scanf("%d", &data) != 1 || data == 0)
            break;
        next = malloc(sizeof(struct z));
        if (next == NULL) {
            printf("Error creating next node no. %d", x - 1);
            return NULL;
        }
        node->next = next;
        node = next;
        node->a = data;
        node->next = NULL;
    }
    return head;
}

int main(void) {
    struct z *head = CreateList();
    struct z *node;
    for (node = head; node != NULL; node = node->next) {
        printf("%d ", node->a);
    }
    printf("\n");
    return 0;
}

我認為您的問題是全局變量。 使它們進入功能,至少是節點和下一個。 在實際添加值時按需創建它們。 作為最后的提示,在這種情況下,do-while循環會使您的代碼看上去比現在更干凈,肯定會減少代碼重復。

暫無
暫無

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

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