关于链栈的有关问题。为什么输入数据后,输出异常啊求教
关于链栈的问题。为什么输入数据后,输出错误啊?求教。
#include<stdio.h>
#include<malloc.h>
#define N 6
typedef int elemtype;
typedef struct stacknode{
elemtype data;
struct stacknode *next;
}StackNode;
StackNode *InitStack(StackNode *top){
top=(StackNode *)malloc(sizeof(StackNode));
top->next=NULL;
return top;
}
int Judge(StackNode *top){
if(top->next==NULL)
{
printf("建栈成功...\n");
return 1;
}
else
{
printf("建栈失败!\n");
return 0;
}
}
int Push(StackNode *top){
StackNode *p;
int i,item;
for(i=0;i<N;i++)
{
printf("请输入第%d个值item\n",i+1);
scanf("%d",item);
p=(StackNode *)malloc(sizeof(StackNode));
p->next=NULL;
p->data=item;
p->next=top;
top=p;
}
return 1;
}
int Output(StackNode *top){
int i;
for(i=0;i<N;i++)
{
printf("%d ",top->data);
top=top->next;
}
return 1;
}
int main()
{
StackNode *top;
top=InitStack(top);
Judge(top);
Push(top);
printf("链式栈的输出(从栈顶到栈底)\n");
Output(top);
return 0;
}
------解决方案--------------------
同时Push这个函数的返回值类型改成StackNode *,然后在函数中返回top
#include<stdio.h>
#include<malloc.h>
#define N 6
typedef int elemtype;
typedef struct stacknode{
elemtype data;
struct stacknode *next;
}StackNode;
StackNode *InitStack(StackNode *top){
top=(StackNode *)malloc(sizeof(StackNode));
top->next=NULL;
return top;
}
int Judge(StackNode *top){
if(top->next==NULL)
{
printf("建栈成功...\n");
return 1;
}
else
{
printf("建栈失败!\n");
return 0;
}
}
int Push(StackNode *top){
StackNode *p;
int i,item;
for(i=0;i<N;i++)
{
printf("请输入第%d个值item\n",i+1);
scanf("%d",item);
p=(StackNode *)malloc(sizeof(StackNode));
p->next=NULL;
p->data=item;
p->next=top;
top=p;
}
return 1;
}
int Output(StackNode *top){
int i;
for(i=0;i<N;i++)
{
printf("%d ",top->data);
top=top->next;
}
return 1;
}
int main()
{
StackNode *top;
top=InitStack(top);
Judge(top);
Push(top);
printf("链式栈的输出(从栈顶到栈底)\n");
Output(top);
return 0;
}
------解决方案--------------------
同时Push这个函数的返回值类型改成StackNode *,然后在函数中返回top