栈的顺序存储结构和操作实现

头文件Stack.h

#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
typedef int ElemType;
typedef struct SequStack
{
	ElemType* stack; 
	int top;
	int MaxSize;
}Stack;
#endif

栈在顺序存储下运算的算法.c`

#include <stdio.h>
#include <stdlib.h>
#include "Stack.h"
/***********************************/
//初始化栈S为空
/**********************************/
void initStack(Stack* S,int ms)
{
	if(ms<10)
	{
		S->MaxSize=10;
	}
	else
	{
		S->MaxSize=ms;
	}
	S->stack=calloc(S->MaxSize,sizeof(ElemType));
	if(!S->stack)
	{
		printf("分配空间失败!\n");
		exit(1);
	}
	S->top=-1;//初始化栈顶为空 
 }
/***********************************************************/
//元素item进栈
/***********************************************************/
void push(Stack* S,ElemType item)
{
	if(S->top==S->MaxSize-1)
	{
		S->stack=realloc(S->stack,2*sizeof(S->stack)*S->MaxSize);
	}
	if(!S->stack)
	{
		printf("重新分配空间失败!\n");
		exit(1);
	}
	S->MaxSize=2*S->MaxSize;
	
	S->top++;
	S->stack[S->top]=item; 
 }
/*********************************************************/
//删除栈顶元素并返回
/*********************************************************/
ElemType pop(Stack* S)
{
	if(S->top==-1)
	{
		printf("栈空无法删除,退出运行!\n");
		exit(1);
	}
	return S->stack[S->top--];
 } 
/*********************************************************/
//读取栈顶元素的值
/*********************************************************/
ElemType peek(Stack* S)
{
	if(S->top==-1)
	{
		printf("栈空无法读取!,退出运行!");
		exit(1); 
	}
	return S->stack[S->top];
 } 
/*********************************************************/
//判断栈是否为空
/*********************************************************/
int emptyStack(Stack* S)
{
	return S->top==-1;
 } 
/*********************************************************/
//清除栈中所有元素
/********************************************************/
void clearStack(Stack* S)
{
	if(S->stack!=NULL)
	{
		free(S->stack);
		S->stack=NULL;
		S->top=-1;
		S->MaxSize=0;
	}
 } 
/*********************************************************/

主函数

#include <stdio.h>
#include <stdlib.h>
#include "Stack.h"
#include "栈在顺序存储下运算的算法.c"
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(int argc, char *argv[]) 
{
	int i,x,y,z;
	int a[8]={3,8,5,17,9,30,15,22};
	Stack r,*S=&r;
	
	initStack(S,1);
	
	for(i=0;i<8;i++)
	{
		push(S,a[i]);
	
	}
	x=pop(S);
	y=pop(S);
	z=pop(S);
	printf("%d %d %d\n",x,y,z);
	push(S,68);
	x=peek(S);
	y=pop(S);
	z=peek(S);
	printf("%d %d %d\n",x,y,z);
	
	push(S,60);
	
	while(!emptyStack(S))
	{
		printf("%d",pop(S));
		printf("\n");
	}
	clearStack(S);
	return 0;
}

运行结果
在这里插入图片描述
参考 数据结构 徐孝凯著

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值