//C语言版
#include <stdlib.h>
#include <iostream>
using namespace std;
const int EmptyToS=-1;
const int MinStackSize=5;
const int MaxStackSize=30;
struct StackRecord
{
int Capacity;
int TopofStack;
char *Array;
};
typedef StackRecord *MyStack;
MyStack CreateStack(int MaxElements)
{
MyStack S;
if(MaxElements<MinStackSize)
{
cout<<"Stack size is too small"<<endl;
return 0;
}
S=(StackRecord*)malloc(sizeof(struct StackRecord));
if(S==NULL)
{
cout<<"Out of space"<<endl;
return 0;
}
S->Capacity=MaxElements;
S->TopofStack=EmptyToS;
S->Array=(char *)malloc(sizeof(char)*MaxElements);
return S;
}
void DisposeStack(MyStack S)
{
if (S!=NULL)
{
free(S->Array); //注意释放顺序
free(S);
}
}
int IsEmpty(MyStack S)
{
return S->TopofStack==EmptyToS;
}
bool IsFull(MyStack S)
{
if(S->TopofStack==(MaxStackSize-1))
return true;
return false;
}
void Push(char x,MyStack S)
{
if(IsFull(S))
cout<<"Full stack"<<endl;
else
S->Array[++S->TopofStack]=x;
}
void Pop(MyStack S)
{
if(IsEmpty(S))
cout<<"Empty stack"<<endl;
else
S->TopofStack--;
}
char TopAndPop(MyStack S)
{
if(!IsEmpty(S))
return S->Array[S->TopofStack--];
cout<<"Empty Stack"<<endl;
return 0;
}
void PrintStack(MyStack S)
{
for(int i=0;i!=(S->TopofStack+1);i++)
cout<<S->Array[i]<<endl;
}
int main()
{
MyStack S=CreateStack(10);
Push('1',S);
Push('2',S);
Push('3',S);
PrintStack(S);
cout<<TopAndPop(S)<<endl;
PrintStack(S);
cout<<TopAndPop(S)<<endl;
cout<<TopAndPop(S)<<endl;
cout<<TopAndPop(S)<<endl;
return 0;
}
//C++版本
//MyStack.h
typedef char DataType;
const int MaxStackSize=50;
class MyStack
{
private:
DataType Stacklist[MaxStackSize];
int TopofStack;
public:
MyStack(void);
~MyStack(void);
void PushStack(const DataType&Item);
DataType PopStack();
void ClearStack();
//访问栈顶元素
DataType PeekStack() const;
bool Empty() const;
bool Full() const;
};
//MyStack.cpp
#include "MyStack.h"
#include "iostream"
#include <stdlib.h>
using std::cout;
using std::endl;
MyStack::MyStack(void)
{
TopofStack=-1;
}
MyStack::~MyStack(void)
{
}
void MyStack::PushStack( const DataType&Item )
{
if(TopofStack==MaxStackSize-1)
{
cout<<"stack overflow"<<endl;
exit(1);
}
Stacklist[++TopofStack]=Item;
}
DataType MyStack::PopStack()
{
if(TopofStack==-1)
{
cout<<"stack is empty"<<endl;
exit(1);
}
return Stacklist[TopofStack--];
}
void MyStack::ClearStack()
{
TopofStack=-1;
}
DataType MyStack::PeekStack() const
{
if(TopofStack==-1)
{
cout<<"stack is empty"<<endl;
exit(0);
}
return Stacklist[TopofStack];
}
bool MyStack::Empty() const
{
if(-1==TopofStack)
return true;
return false;
}
bool MyStack::Full() const
{
if(TopofStack==(MaxStackSize-1))
return true;
return false;
}
int main()
{
MyStack S;
S.PushStack('1');
S.PushStack('2');
cout<<S.PeekStack()<<endl;
S.PopStack();
cout<<S.PeekStack()<<endl;
S.ClearStack();
cout<<S.PeekStack()<<endl;
return 0;
}