@qiezhian
2014-11-15T08:44:48.000000Z
字数 1202
阅读 1024
programming
/*
Filename: stack.h
Function: Implemention of stack that can compatible with some
basic data types like int,char even some custom class
Details:
*/
#include <iostream>
#define MAXNUM 10
using namespace std;
template<class Item>
struct StackNode
{
Item s[MAXNUM];
StackNode* next;
};
template<class Item>
class MyStack
{
private:
StackNode<Item>* head;
int top;
public:
MyStack();
~MyStack();
Item Pop();
void Push(Item item);
int IsEmpty();
};
template<class Item>
MyStack<Item>::MyStack()
{
head=NULL;
top=0;
}
template<class Item>
MyStack<Item>::~MyStack()
{
while(NULL != head)
{
StackNode<Item>* tmp=head->next;
delete head;
head=tmp;
}
}
template<class Item>
Item MyStack<Item>::Pop()
{
if(IsEmpty())
{
cout<<"stack is empty,cannot pop any more!"<<endl;
return ((head->s)[top]);
}
if(top==-1)
{
StackNode<Item>* tmp=head->next;
delete head;
head=tmp;
top=MAXNUM-1;
}
return ((head->s)[top--]);
}
template<class Item>
void MyStack<Item>::Push(Item item)
{
if(head==NULL)
{
head=new StackNode<Item>;
if(head==NULL)
{
cout<<"initial stack error----malloc error"<<endl;
return ;
}
top=0;
}
top++;
if(top==MAXNUM)
{
StackNode<Item>* NewNode=new StackNode<Item>;
NewNode->next=head;
head=NewNode;
top=0;
}
(head->s)[top]=item;
}
template<class Item>
int MyStack<Item>::IsEmpty()
{
return ((head==NULL)||((head->next==NULL)&&(top==0)));
}