头文件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;
}
运行结果
参考 数据结构 徐孝凯著