2-4 另类堆栈 (20分)
在栈的顺序存储实现中,另有一种方法是将Top定义为栈顶的上一个位置。请编写程序实现这种定义下堆栈的入栈、出栈操作。如何判断堆栈为空或者满?
函数接口定义:
bool Push( Stack S, ElementType X ); ElementType Pop( Stack S );
其中Stack结构定义如下:
typedef int Position
;
typedef struct SNode
*PtrToSNode
;
struct SNode
{
ElementType
*Data
;
Position Top
;
int MaxSize
;
};
typedef PtrToSNode Stack
;
注意:如果堆栈已满,Push函数必须输出“Stack Full”并且返回false;如果队列是空的,则Pop函数必须输出“Stack Empty”,并且返回ERROR。
裁判测试程序样例:
#include <stdio.h>
#include <stdlib.h>
#define ERROR -1
typedef int ElementType
;
typedef enum { push
, pop
, end
} Operation
;
typedef enum { false
, true
} bool
;
typedef int Position
;
typedef struct SNode
*PtrToSNode
;
struct SNode
{
ElementType
*Data
;
Position Top
;
int MaxSize
;
};
typedef PtrToSNode Stack
;
Stack
CreateStack( int MaxSize
)
{
Stack S
= (Stack
)malloc(sizeof(struct SNode
));
S
->Data
= (ElementType
*)malloc(MaxSize
* sizeof(ElementType
));
S
->Top
= 0;
S
->MaxSize
= MaxSize
;
return S
;
}
bool
Push( Stack S
, ElementType X
);
ElementType
Pop( Stack S
);
Operation
GetOp();
void PrintStack( Stack S
);
int main()
{
ElementType X
;
Stack S
;
int N
, done
= 0;
scanf("%d", &N
);
S
= CreateStack(N
);
while ( !done
) {
switch( GetOp() ) {
case push
:
scanf("%d", &X
);
Push(S
, X
);
break;
case pop
:
X
= Pop(S
);
if ( X
!=ERROR
) printf("%d is out\n", X
);
break;
case end
:
PrintStack(S
);
done
= 1;
break;
}
}
return 0;
}
输入样例:
4
Pop
Push
5
Push
4
Push
3
Pop
Pop
Push
2
Push
1
Push
0
Push
10
End
输出样例:
Stack Empty
3 is out
4 is out
Stack Full
0 1 2 5
AC
第一次写堆栈的题目,写了不少的时间,现在还没有任何头绪啊啊
bool
Push( Stack S
, ElementType X
)
{
if(S
->Top
<S
->MaxSize
)
{
S
->Data
[S
->Top
++]=X
;
return true
;
}
else
{
printf("Stack Full\n");
return false
;
}
}
ElementType
Pop( Stack S
)
{
if(S
->Top
>0)
{
S
->Top
--;
return S
->Data
[S
->Top
];
}
else
{
printf("Stack Empty\n");
return ERROR
;
}
}
2020.11.01了,现在回头看看之前难到我跪下的题目,没有那么了不起,万事都得磨。 加油,尾款人。