问题出在while循环上.我找不到什么是错的.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
typedef struct node {
int data;
node *next;
};
int main(){
node * root= (node *) malloc(sizeof(node));
node * temp = root;
for(int i=0;i<10;i++){
temp->data=i*10;
temp->next=(node *) malloc(sizeof(node));
temp=temp->next;
}
temp =root;
while(temp){ //infinite loop
printf("\n%d",temp->data);
temp=temp->next;
}
getch();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您永远不会将最后一个节点设置为null.放在
temp->next = NULL;
for循环之后.
使用malloc分配节点时,值不会初始化为任何值.所以next指向内存中的一些随机位置.
| 归档时间: |
|
| 查看次数: |
2221 次 |
| 最近记录: |