创建含25-75个0-100随机数的Linked List无输出问题求助
链表程序无输出且无限循环问题排查
问题描述
需要创建包含25至75个0-100之间随机整数的链表并显示,但运行程序后控制台无输出、无报错且无法自行结束。期望输出示例:
Ex. The list is: 0, 0, 1, 4, 5, 6, 8, 9, 12, 13, 14, 17, 19, 20, 20, 23, 24, 25, 25, 26, 28, 30, 30, 32, 34, 36, 37, 38, 43, 44, 46, 50, 53, 54, 54, 62, 62, 65, 66, 66, 68, 70, 70, 74, 79, 79, 80, 82, 83, 85, 85, 89, 96, 97,
问题分析与修正
1. 无限循环的核心错误
main函数中的for循环条件误用了赋值操作而非比较操作:
// 错误写法 for(i = 0; i = listcount-1; i++){
i = listcount-1会将listcount-1的值赋给i,该表达式结果永远为真(listcount最小为25,listcount-1不为0),导致循环无限执行,程序永远无法走到display函数。
修正为:
// 正确写法:循环listcount次 for(i = 0; i < listcount; i++){
或等价的i <= listcount-1。
2. 插入逻辑与期望输出不符
当前insert函数的while循环条件num2 <= current->data会生成降序列表,与用户期望的升序输出不符。需将条件改为num2 >= current->data,这样才能找到第一个大于当前数值的节点,将新节点插入其前方,实现升序排列。
修正后的insert函数核心部分:
// 修正条件,实现升序插入 while(NULL != current && num2 >= current->data){ previous = current; current = current->next; }//end of while
修正后的完整代码
#include <stdio.h> #include <stdlib.h> #include <time.h> //Self Referential Structure struct node{ int data; struct node *next; }; //Type Definitions typedef struct node Node; typedef struct node* NodePointer; //Function Prototypes void insert(int, NodePointer *); void display(NodePointer); //Insert Function void insert(int num2, NodePointer *head2){ NodePointer newNode = NULL; NodePointer previous = NULL; NodePointer current = *head2; newNode = malloc(sizeof(Node)); if(NULL != newNode){ newNode->data = num2; // 修正条件,实现升序插入 while(NULL != current && num2 >= current->data){ previous = current; current = current->next; }//end of while if(NULL == previous){ newNode->next = current; *head2 = newNode; }//end of if else{ previous->next = newNode; newNode->next = current; }//end of else }//end of if }//end of function //Display Function void display(NodePointer current){ if(NULL == current){ printf("The linked list is empty!\n\n"); return; } printf("The list is: "); while(NULL != current){ printf("%i, ", current->data); current = current->next; } printf("\n\n"); } //MAIN FUNCTION int main(){ int i = 0; int listcount = 0; int num = 0; NodePointer head = NULL; srand(time(NULL)); listcount = rand() % (75 + 1 - 25) + 25; // 修正循环条件,避免无限循环 for(i = 0; i < listcount; i++){ num = rand() % 100; insert(num, &head); } display(head); return 0; }
内容的提问来源于stack exchange,提问作者Erin
相关产品推荐
相关产品推荐

