HZNUOJ

【数据结构】栈(Stack)的数组实现

Tags:
Time Limit:  1 s      Memory Limit:   128 MB
Submission:326     AC:90     Score:96.29

Description

栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。   

-----------From 百度百科

 

现在对希望你对于给定的Stack结构体完成以下几类操作:

1.  Status Push(SqStack *S,SElemType *e)    //将e压入栈中

2.  Status Pop(SqStack *S,SElemType *e)     //将栈顶元素从栈中取出

3.  Status StackTraverse(SqStack *S)        //从下到上输出栈内元素

 

详细要求如下:

1.  对于S,将e压入栈中,成为栈顶元素

2.  对于S,将该栈中的栈顶元素取出

3.  对于S,自下向上输出栈内元素,每个元素之间用空行隔开,若栈空则输出空行

 

Tips:主体代码已给出,你只需要提交函数

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <string.h>

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 100

typedef int Status;
typedef int SElemType;
typedef struct
{
	SElemType data[MAXSIZE];
	int top;
}SqStack;

Status InitStack(SqStack *S)
{
	S->top = -1;
	return OK;
}

Status ClearStack(SqStack *S)
{
	S->top = -1;
	return OK;
}

Status StackEmpty(SqStack *S)
{
	if (S->top == -1)
		return TRUE;
	else
		return FALSE;
}

int StackLength(SqStack *S)
{
	return S->top + 1;
}

Status GetTop(SqStack *S, SElemType *e)
{
	if (S->top == -1)
		return ERROR;
	else
		*e = S->data[S->top];
	return OK;
}
Status Push(SqStack *S, SElemType e);
Status Pop(SqStack *S, SElemType *e);
Status StackTraverse(SqStack *S);
int main()
{
	SqStack s;
	InitStack(&s);
	int n;
	scanf("%d", &n);
	char ctl[10];
	while (n--)
	{
		scanf("%s", ctl);
		if (strcmp(ctl, "Push") == 0)
		{
			int x;
			scanf("%d", &x);
			Push(&s, x);
		}
		else if (strcmp(ctl, "Pop") == 0)
		{
			int x;
			if (Pop(&s, &x))
				printf("%d\n", x);
			else printf("Error: Stack is empty!\n");
		}
		else if (strcmp(ctl, "ShowAll") == 0)
		{
			StackTraverse(&s);
		}
	}
	ClearStack(&s);
	return 0;
}

Input

根据题目要求补全函数

Samples

input
8 Push 2 Push 3 Pop Pop Pop Push 4 Push 6 ShowAll
output
3 2 Error: Stack is empty! 4 6