【C语言】【数据结构】顺序栈的基本操作(创建、入栈、出栈、栈的长度、栈顶元素、遍历)

创建空的顺序栈,栈的入栈、出栈、返回栈的长度、返回栈顶元素、栈的遍历:

#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;
}
  • 11
    点赞
  • 69
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值