C++链表最大值打印异常及程序卡顿问题求助
问题诊断与修复方案
我一眼就找到导致程序卡顿的核心问题了——你的Max函数里藏着一个死循环!
先看你出问题的代码片段:
int Max(struct node *p) { int max = -100; while (p != NULL) { if (p->data > max) { max = p->data; p = p->next; // 只有当前值大于max时才移动指针! } } return max; }
你把p = p->next放在了if的代码块里,这意味着如果当前节点的data不大于max,指针p就不会向下移动,循环会一直卡在这个节点上,永远无法退出,自然就出现了卡顿现象。
修复后的Max函数
只需要把指针移动的语句移到if外面,确保每次循环都能推进指针:
int Max(struct node *p) { int max = -100; while (p != NULL) { if (p->data > max) { max = p->data; } p = p->next; // 不管是否更新max,都要移动到下一个节点 } return max; }
另外两个需要修正的小问题
- 缺少
iostream头文件:你在main里用了cout,但没有包含对应的头文件,这会导致编译错误。需要在顶部添加:
#include <iostream>
- C++风格优化(非卡顿原因):虽然
malloc能正常工作,但在C++中更推荐使用new来分配内存,比如把malloc的语句换成:
first = new node; // 以及后面的 t = new node;
完整修复后的代码
#include <stdlib.h> #include <stdio.h> #include <iostream> // 新增头文件 using namespace std; struct node { int data; struct node *next; } *first = NULL; void create(int a[], int n) { int i; struct node *t, *last; first = new node; // 改用new first->data = a[0]; first->next = NULL; last = first; for (i = 1; i < n; i++) { t = new node; // 改用new t->data = a[i]; t->next = NULL; last->next = t; last = t; } } void display(struct node *p) { while (p != NULL) { printf("%d ", p->data); p = p->next; } } int Max(struct node *p) { int max = -100; while (p != NULL) { if (p->data > max) { max = p->data; } p = p->next; // 修复死循环的关键 } return max; } int main() { int m = 0; int a[] = { 3, 5, 7, 10, 15, 8, 12, 20 }; create(a, 8); display(first); printf("\n"); m = Max(first); cout << "The maximum of the linked list is : " << m; return 0; }
现在运行这个代码,就能正常输出链表内容和最大值20了。
内容的提问来源于stack exchange,提问作者Ashish
相关产品推荐
相关产品推荐

