各位高手!请帮小弟看看这程序为什么会出现死循环!谢谢了!
#include <stdlib.h>
struct list
{
int data;
struct list *next;
};
typedef struct list stack;
typedef stack* Link;
Link top=NULL;
/*将数据压入堆栈*/
void push(int item)
{
Link new_node;
new_node=(Link)malloc(sizeof(stack));
new_node-> data=item;
top=new_node;
new_node-> next=top;
}
int pop()
{
int temp;
Link ding;
if(top!=NULL)
{
ding=top;
top=top-> next;
temp=ding-> data;
free(ding);
return temp;
}
else
return -1;
}
void main()
{
int temp;
int select;
Link point=NULL;
printf( "\n1.Input:\n ");
printf( "2.Output\n ");
printf( "Exit\n ");
scanf( "%d ",&select);
do
{
switch(select)
{
case 1: printf( "Input a data: ");
scanf( "%d ",&temp);
push(temp);
point=top;
while(point!=NULL)
{
printf( "%d\n ",point-> data);
point=point-> next;
}
break;
case 2: if((temp=pop())==-1)
printf( "The list is empty\n ");
else
{
printf( "The output is %d ",temp);
point=top;
while(point!=NULL)
{ printf( "The afterdata is%d\n ",point-> data);
point=point-> next;
}
}
break;
}
printf( "\n1.Input:\n ");
printf( "2.Output\n ");
printf( "Exit ");
scanf( "%d ",&select);
}while(select!=3);
printf( "\nThank You\n ");
system( "pause ");
}
[解决办法]
void push(int item)
{
Link new_node;
new_node=(Link)malloc(sizeof(stack));
new_node-> data=item;
new_node-> next=top;
top=new_node;
}
new_node-> next=top;
top=new_node;
这两句换一个位置就行了
[解决办法]
上面的朋友说的对,你这样将链的头指向新结点,又将新结点的next指针指向链头,这就形成了一个指针之间的循环,只要按上面朋友所说,将 new_node-> next = top 与 top = new_node 相互换一下位置即可。