|
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 函数中,需要增加栈满的判断。
修改后代码:
- #include <stdio.h>
- #include <stdlib.h> // 添加stdlib.h以使用malloc和free
- #define MAXSIZE 10
- typedef struct {
- int data[MAXSIZE];
- int top1;
- int top2;
- } DStack;
- void InitDStack(DStack *&s) {
- s = (DStack *)malloc(sizeof(DStack)); // 为DStack分配内存
- s->top1 = -1;
- s->top2 = MAXSIZE;
- }
- bool StackFull(DStack *s) {
- return s->top1 + 1 == s->top2;
- }
- bool Push(DStack *&s, int e, int which) {
- if (StackFull(s)) {
- return false;
- }
- if (which == 1) {
- s->data[++s->top1] = e;
- } else if (which == 2) {
- s->data[--s->top2] = e;
- }
- return true;
- }
- bool Pop(DStack *&s, int &e, int which) {
- if (which == 1 && s->top1 != -1) {
- e = s->data[s->top1--];
- return true;
- } else if (which == 2 && s->top2 != MAXSIZE) {
- e = s->data[s->top2++];
- return true;
- }
- return false;
- }
- int main() {
- DStack *s;
- int e;
- InitDStack(s);
- Push(s, 1, 1);
- Push(s, 2, 1);
- Push(s, 3, 2);
- if (Pop(s, e, 1)) {
- printf("出栈:%d\n", e);
- } else {
- printf("栈为空或者出现错误\n");
- }
-
- // 清理分配的内存
- free(s);
-
- return 0;
- }
复制代码
|
最佳答案
查看完整内容
代码中存在几个问题导致没有按预期输出值:
[*]在 main 函数中,你声明了 DStack *s 指针,但没有为它分配内存。你需要使用 malloc 或者在栈上分配内存。
[*]在 Push 和 Pop 函数中,你应该检查栈是否已满或为空,以防止溢出或下溢。
[*]在 Push 函数中,需要增加栈满的判断。
修改后代码:
|