【C語言】【數據結構】順序棧的基本操作(建立、入棧、出棧、棧的長度、棧頂元素、遍歷)

2020-08-10 16:13:02

建立空的順序棧,棧的入棧、出棧、返回棧的長度、返回棧頂元素、棧的遍歷:

#include <stdio.h>
#include <stdlib.h>
#define ERROR 0
#define OK 1
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10

typedef int Status;
typedef int SElemType;
typedef struct{
	SElemType *base, *top;
	int stacksize;
}SqStack;

Status InitStack(SqStack & );	//空棧 
Status Push(SqStack & , SElemType );	//入棧 
Status Pop(SqStack & , SElemType & );	//出棧 
int StackLength(SqStack );	//棧的長度 
Status GetTop(SqStack , SElemType & );	//返回棧頂元素 
Status StackTraverse(SqStack );	//遍歷

int main()
{
	SqStack S;
	int a;
	SElemType e;
	
	if(!InitStack(S)) printf("Create Error!\n");
	while(1)
	{
		printf("1:Push\n2:Pop\n3:Get the top\n4:return the length of the stack\n5:load the stack\n0:exit\nplease choose: \n");
		scanf("%d", &a);
		switch(a)
		{
			case 1: scanf("%d", &e);
					if(!Push(S,e)) printf("Push Error!\n\n");
					else printf("The element %d is successfully pushed!\n\n", e);
					break;
			case 2: if(!Pop(S,e)) printf("Pop Error!\n\n");
					else printf("The element %d is successfully poped!\n\n", e);
					break;
			case 3: if(!GetTop(S,e)) printf("Get Top Error!\n\n");
					else printf("The top element is %d!\n\n", e);
					break;
			case 4: printf("The length of the stack is %d\n\n", StackLength(S));
					break;
			case 5: StackTraverse(S);
					printf("\n");
					break;
			case 0: return OK;
		}
	}
}

Status InitStack(SqStack &S)
{
	S.base = (SElemType *) malloc (STACK_INIT_SIZE * sizeof(SElemType));
	if(!S.base) return ERROR;
	S.top = S.base;
	S.stacksize = STACK_INIT_SIZE;
	return OK;
}

Status Push(SqStack &S, SElemType e)
{
	if(S.top - S.base >= S.stacksize)
	{
		S.base = (SElemType *) realloc (S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemType));
		if(!S.base) return ERROR;
		S.top = S.base + S.stacksize;
		S.stacksize += STACKINCREMENT;
	}
	*S.top++ = e;
	return OK;
}

Status Pop(SqStack &S, SElemType &e)
{
	if(S.base == S.top) return ERROR;
	e = *--S.top;
	return OK;
}

int StackLength(SqStack S)
{
	return(S.top-S.base);
}

Status GetTop(SqStack S, SElemType &e)
{
	if (S.top == S.base) return ERROR;
	e = *(S.top-1);
	return OK; 
}

Status StackTraverse(SqStack S)
{
	SElemType *p;
	
	p = S.top;
	if(S.base == p) printf("The stack is empty!\n");
	else
		for(p--; p>=S.base; p--)
			printf("%d ", *p);
	printf("\n");
	return OK;
}