// CTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
typedef int ElemType;
struct Stack{
ElemType *stack;
int top;
int maxSize;
};
void InitStack(Stack& s){
s.maxSize =10;//设置栈空间的大小为10个元素的位置
s.stack = new ElemType[s.maxSize];
if(!s.stack){
cerr<<"动态存储分配失败"<<endl;
exit(1);
}
s.top=-1;//初始栈为空cf
}
void Push(Stack &s,ElemType item){//元素item进栈,即插入到栈顶
if(s.top==s.maxSize-1){
int k = sizeof(ElemType);
s.stack = (ElemType *)realloc(s.stack,2*s.maxSize*k);
s.maxSize = 2*s.maxSize;
}
s.top++;
s.stack[s.top]=item;
}
ElemType Pop(Stack &s){//删除栈顶元素,并返回
if(s.top==-1){
cerr<<"Stack is empty!"<<endl;
//exit(1);
}
s.top--;
return s.stack[s.top+1];
}
ElemType Peek(Stack &s){//读取栈顶的元素
if(s.top==-1){
cerr<<"Stack is empty!"<<endl;
exit(1);
}
return s.stack[s.top];
}
bool EmptyStack(Stack &s){//清空栈
return s.top == -1;
}
void ClearStack(Stack &s){
if(s.stack){
delete []s.stack;
s.stack = 0;
}
s.top = -1;
s.maxSize = 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
Stack s;
InitStack(s);//初始化栈
int a[8]={3,8,5,17,9,30,15,22};
for(int i=0;i<8;i++){//将数据插入到栈顶
Push(s,a[i]);
}
cout<<Pop(s);
cout<<' '<<Pop(s)<<endl;
Push(s,86);
cout<<Peek(s);
cout<<' '<<Pop(s)<<endl;
while(!EmptyStack(s)){//如果栈不为空
cout<<Pop(s)<<' ';
}
cout<<endl;
ClearStack(s);
system("pause");
return 0;
}