|
|
悬赏10鱼币已解决
#include<stdio.h>
#define MAXSIZE 10
typedef struct {
int data[MAXSIZE];
int top1;
int top2;
} DStack;
void InitDStack(DStack *&s) {
s->top1 = -1;
s->top2=MAXSIZE;
}
bool StackEmpty(DStack *s, int which) {
if(which==1)
{
return(s->top1==-1);
}
if(which==2)
{
return(s->top2==MAXSIZE);
}
}
bool StackFull(DStack *s)
{
return s->top1+1==s->top2;
}
bool Push(DStack *&s, int e, int which) {
// which指示新元素e进哪个栈
if(which==1)
{
s->data[++s->top1]=e;
}
if(which==2)
{
s->data[--s->top2]=e;
}
return true;
}
bool Pop(DStack *&s, int &e, int which) {
// which指示从哪个栈弹出栈顶元素赋给e
if(which==1)
{
e=s->data[s->top1--];
}
if(which==2)
{
e=s->data[s->top2++];
}
return true;
}
bool GetTop(DStack *s, int &e, int which) {
// which指示取哪个栈的栈顶元素赋给e
if(which==1)
{
e=s->data[s->top1];
}
if(which==2)
{
e=s->data[s->top2];
}
return true;
}
int main()
{
DStack *s;
int e;
InitDStack(s);
Push(s,1,1);
Push(s,2,1);
Push(s,3,2);
Pop(s,e,1);
printf("出栈:%d\n",e);
return 0;
}
为什么输出没有值?怎么修改呢? |
最佳答案
查看完整内容
代码中存在几个问题导致没有按预期输出值:
[*]在 main 函数中,你声明了 DStack *s 指针,但没有为它分配内存。你需要使用 malloc 或者在栈上分配内存。
[*]在 Push 和 Pop 函数中,你应该检查栈是否已满或为空,以防止溢出或下溢。
[*]在 Push 函数中,需要增加栈满的判断。
修改后代码:
|