alternative stack
In the sequential storage implementation of the stack, another method is to define Top as the previous position of the top of the stack. Please write a program to realize the push and pop operations of the defined lower stack. How to judge whether the stack is empty or full?
Function interface definition:
bool Push( Stack S, ElementType X );
ElementType Pop( Stack S );
where Stack
the structure is defined as follows:
typedef int Position;
typedef struct SNode *PtrToSNode;
struct SNode {
ElementType *Data; /* 存储元素的数组 */
Position Top; /* 栈顶指针 */
int MaxSize; /* 堆栈最大容量 */
};
typedef PtrToSNode Stack;
Note: If the stack is full, Push
the function must output "Stack Full" and return false; if the queue is empty, the Pop
function must output "Stack Empty" and return ERROR.
Sample referee test procedure:
#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;
}
/* 你的代码将被嵌在这里 */
Input sample:
4
Pop
Push 5
Push 4
Push 3
Pop
Pop
Push 2
Push 1
Push 0
Push 10
End
Sample output:
Stack Empty
3 is out
4 is out
Stack Full
0 1 2 5
代码长度限制 16 KB
时间限制 400 ms
内存限制 64 MB
Answer:
bool Push( Stack S, ElementType X ){
if(S->Top==S->MaxSize)
{
printf("Stack Full\n");
return false;
}
else
{
S->Data[S->Top]=X;
S->Top++;
}
return true;
}
ElementType Pop( Stack S )
{
if(S->Top==0)
{
printf("Stack Empty\n");
return ERROR;
}
else
{
S->Top--;
}
return S->Data[S->Top];
}