我的反向链表程序无法打印反向整数列表

问题描述 投票:0回答:1

我编写了一个 C 程序,该程序应该根据整数的输入方式以相反的顺序打印出整数的链接列表。然而,由于某种原因,程序没有打印出反向链表。

这是我使用的代码:

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

struct node {
        int value;
        struct node* next;
};

struct node* create_node(int value) {
        struct node* new_node = (struct node*)malloc(sizeof(struct node));
        if (new_node == NULL) {
                printf("Error allocating memory.\n");
                exit(1);
        }
        new_node->value = value;
        new_node->next = NULL;
        return new_node;
}

void insert_node_end (struct node** head, int value) {
        struct node* new_node = create_node(value);
        if (*head == NULL) {
                *head = new_node;
        } else {
                struct node* current = *head;
                while (current->next != NULL) {
                        current = current->next;
                }
                current->next = new_node;
        }
}

struct node* reverse_list(struct node* head) {
        struct node* prev = NULL;
        struct node* current = head;
        struct node* next = NULL;

        while (current != NULL) {
                next = current->next;
                current->next = prev;
                prev = current;
                current = next;
        }

        return prev;
}

int main() {
        struct node* head = NULL;
        int value;

        printf("Enter a list of integers. Press ctrl-d to finish.\n");
        while (scanf("%d", &value) != EOF) {
                insert_node_end(&head, value);
        }

        printf("Data entered in the list:\n");
        while (head != NULL) {
                printf("%d ", head->value);
                head = head->next;
        }
        printf("\n");

        head = reverse_list(head);

        printf("List in reverse order:\n");
        while (head != NULL) {
                printf("%d ", head->value);
                head = head->next;
        }
        printf("\n");

        return 0;
}

这就是应该发生的事情:

Enter a list of integers. Press ctrl-d to finish.
7
6
5
Data entered in the list:
7 6 5 
List in reverse order:
5 6 7

只不过这个程序不会以相反的顺序打印出列表,而是将其留空,如下所示。

Enter a list of integers. Press ctrl-d to finish.
7
6
5
Data entered in the list:
7 6 5 
List in reverse order:

你能帮我吗?

c linked-list
1个回答
0
投票

主要问题是您在

head
函数中重新分配了
main
,因此您无法跟踪列表的开始位置。使用临时变量打印出
main
中两个循环中的值:

for(struct node *curr = head; curr; curr = curr->next) {
    printf("%d ", curr->value);
}
© www.soinside.com 2019 - 2024. All rights reserved.