关于栈的!问题出哪里!
#include<stdio.h>#define maxsize 20
int Num_del;
struct stack
{int a[maxsize];
int top[3];
};
void initstack(struct stack s)
{s.top[1]=-1;
s.top[2]=maxsize;
}
int push(struct stack s,int x,int k)
{if(s.top[1]==s.top[2])
{printf("\nstack is full!\n");
return 0;
}
else {if(k==1)
{s.a[s.top[1]]=x;
s.top[1]++;
}
else s.a[s.top[2]]=x;
s.top[2]--;
}
return 1;
}
int pop(struct stack s,int k)
{if(k==1)
{if(s.top[1]!=-1)
{Num_del=s.a[s.top[1]--];
return 1;
}
else printf("stack_1 can't be poped!\n");
return 0;
}
else {if(s.top[2]!=maxsize)
{Num_del=s.a[s.top[2]];
s.top[2]++;
return 1;
}
else printf("STACK_2 can't be poped!\n");
return 0;
}
}
void print(struct stack s)
{int i;
if(pop(s,1)==1)
{printf("The nums of stack_1 are:\n");
for(i=0;i<s.top[1];i++)
printf("%d",s.a[s.top[1]]);
s.top[1]++;
}
else printf("stack_1 is empty!\n");
if(pop(s,2)==1)
{printf("the nums of stack_2 are:\n");
for(i=s.top[2];i>0;i--)
printf("%d",s.a[s.top[2]]);
s.top[2]--;
}
else printf("stack_2 is empty!\n");
}
void main()
{struct stack s;
int x,k,i;
initstack(s);
printf("input which stack the nums will be pushed:");
scanf("%d",&k);
printf("input 8 nums into stack_%d:\n",k);
for(i=0;i<8;i++)
{if(k==1)
{scanf("%d",&s.a[i]);
s.top[1]++;
}
else {if(k==2)
scanf("%d",&s.a[maxsize-1-i]);
s.top[2]--;
}
}
print(s);
printf("input which stack the num will be pushed:");
scanf("%d",&k);
printf("input the num to be pushed into stack_%d:\n",k);
scanf("%d",&x);
push(s,x,k);
print(s);
printf("input which stack the nums will be poped:");
scanf("%d",&k);
printf("input the num to be poped out of stack_%d:\n",k);
print(s);
printf("%d",Num_del);
}
----------------解决方案--------------------------------------------------------
运行后 ,得到是 整屏幕的数字
----------------解决方案--------------------------------------------------------
我这里一输入就出错
那个s.top[1]= -1
下面那个push函数里你直接用了
else {if(k==1)
{s.a[s.top[1]]=x;
s.top[1]++;
}
顺便问一下那个print(s)有什么用的?
----------------解决方案--------------------------------------------------------
print 输出栈 push 进栈 pop 出栈 initstack 对栈 初始化
push函数里直接用了
else {if(k==1)
{s.a[s.top[1]]=x;
s.top[1]++;
}
会有什么结果呢
[[it] 本帖最后由 jinxilee 于 2008-4-14 14:08 编辑 [/it]]
----------------解决方案--------------------------------------------------------
s.top[1]=-1;
s.a[-1]=x;
程序崩溃了
----------------解决方案--------------------------------------------------------