栈采用顺序存储结构,实现如下任务:

栈采用顺序存储结构,实现如下任务:

(1)初始化顺序栈InitStack_Sq(SqStack &S);

(2)扩充空间Increment(SqStack &S);

(2)入栈Push_Sq(SqStack &S,ElemType e);

(4)取栈顶元素GetTop_Sq(SqStack S,ElemType &e);

(5)出栈Pop_Sq(SqStack &S,ElemType &e);

(6)输出顺序栈元素TraverseStack_Sq(SqStack S);

(7)销毁顺序栈DestroyStack_Sq(SqStack S)。

#include <stdio.h>
#include <stdlib.h>

typedef int ElemType;

#define STACK_INIT_SIZE 10
#define STACK_INCREMENT 5
typedef struct
{
	ElemType *elem;
	int top;
	int stacksize;
}SqStack;

void Error(char *s)
{
	printf("%s\n",s);
	exit(1);
}

void InitStack_Sq(SqStack &S)		//初始化
{
	S.elem = new ElemType[STACK_INIT_SIZE];
	if(!S.elem)	Error("Overflow!");
	S.top = -1;
	S.stacksize = STACK_INIT_SIZE;
}

void Increment(SqStack &S)			//扩充空间
{
	ElemType *ns;
	ns = new ElemType[S.stacksize+STACK_INCREMENT];
	if(!ns)	Error("Overflow!");
	for(int i = 0;i<=S.top;i++)
	{
		ns[i]=S.elem[i];
	}
	delete []S.elem;
	S.elem = ns;
	S.stacksize = S.stacksize+STACK_INCREMENT;
}

void Push_Sq(SqStack &S,ElemType e)		//入栈
{
	if(S.top==(S.stacksize-1))	Increment(S);
	S.elem[++S.top]=e;
	
}

void GetTop_Sq(SqStack S,ElemType &e)		//取栈顶元素
{
	if(S.top!=-1)
	{
		e=S.elem[S.top];
	}
	else
	{
		Error("Stack Empty!");
	}
}

void Pop_Sq(SqStack &S,ElemType &e)		//出栈
{
	if(S.top!=-1)
	{
		e=S.elem[S.top];
		S.top=S.top-1;
	}
	else
	{
		Error("Stack Empty!");
	}
}

void TraverseStack_Sq(SqStack S)		//输出顺序栈元素
{
	int i=0;
	while(i!=S.top+1)
	{
		printf("%d ",S.elem[i]);
		i++;
	}
	printf("\n");
}

void DestroyStack_Sq(SqStack S)		//销毁顺序栈
{
	delete []S.elem;
	S.top=-1;
	S.stacksize=0;
}

int main()
{
	SqStack S;
	ElemType n,e;
	int i;

	InitStack_Sq(S);
	scanf("%d",&n);
	for(i=0;i<n;i++)
	{
		scanf("%d",&e);
		Push_Sq(S,e);
	}
	printf("CreateStack_Sq: ");
	TraverseStack_Sq(S);

	GetTop_Sq(S,e);
	printf("Top element is %d\n",e);
	printf("SqStack after GetTop: ");
	TraverseStack_Sq(S);

	Pop_Sq(S,e);
	printf("SqStack after Pop: ");
	TraverseStack_Sq(S);
	
	DestroyStack_Sq(S);
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值