C语言反转链表程序无法输出反转整数列表,请求技术帮助
问题分析与解决
你的问题出在打印原始链表时修改了head指针,导致后续反转操作传入的是NULL,自然无法得到有效的反转链表。
具体问题点
在打印原始链表的循环中,你直接操作了head指针:
printf("Data entered in the list:\n"); while (head != NULL) { printf("%d ", head->value); head = head->next; // 这里把head移到了链表末尾的NULL }
循环结束后,head的值已经是NULL,此时调用reverse_list(head)相当于传入NULL,返回的自然也是NULL,所以反转后的链表为空。
修复方案
打印链表时使用临时指针遍历,保留原head指针的指向:
修改main函数中打印原始链表的部分:
printf("Data entered in the list:\n"); struct node* temp = head; // 用临时指针遍历 while (temp != NULL) { printf("%d ", temp->value); temp = temp->next; // 移动临时指针,不修改原head } printf("\n");
完整修正后的代码
#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"); struct node* temp = head; // 新增临时指针 while (temp != NULL) { printf("%d ", temp->value); temp = temp->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; }
验证效果
运行修正后的代码,输入7、6、5并按Ctrl+D,输出会符合预期:
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
内容的提问来源于stack exchange,提问作者Sebastian Llaurador
相关产品推荐
相关产品推荐

