栈:
//3.2.07
//sstack.h
//------------------------------------------------
const MaxStackSize = 50;
template <class T>
class sstack
{
private:
T stacklist[MaxStackSize];
//栈顶指针
int top;
public:
sstack(void){top = -1;};
//改变栈的操作
void Push(const T& item);
T Pop(void);
void ClearStack(void);
//访问栈顶元素
T Peek(void) const;
//检测栈状态的方法
int StackEmpty(void) const;
int StackFull(void) const;
};
template <class T>
void sstack<T>::Push(const T& item)
{
if(top==MaxStackSize-1)
{
cerr<<"stack overflow!"<<endl;
exit(1);
}
top++;
stacklist[top]=item;
}
template <class T>
T sstack<T>::Pop(void)
{
T temp;
if(top==-1)
{
cerr<<"Atempt to pop an empty stack"<<endl;
exit(1);
}
temp=stacklist[top];
top--;
return (temp);
}
template <class T>
void sstack<T>::ClearStack(void)
{
top=-1;
}
template <class T>
T sstack<T>::Peek(void) const
{
if(top==-1)
{
cerr<<"Atempt to peek an empty stack"<<endl;
exit(1);
}
return (stacklist[top]);
}
template <class T>
int sstack<T>::StackFull(void) const
{
return (top==MaxStackSize-1);
}
template <class T>
int sstack<T>::StackEmpty(void) const
{
return (top==-1);
}
链栈:
//3.2.07
//lstack.cpp
//------------------------------------------------
template <class T>
struct stacknode
{
T data;
stacknode<T>* next;
};
template <class T>
class lstack
{
private:
stacknode<T> *head;
int top;
stacknode<T> *GetNode(const T &item,stacknode<T> *ptr=NULL);
public:
lstack(void){top=-1; head=NULL;};
lstack(const lstack& stack);
~lstack(void);
//改变栈的操作
void Push(const T& item);
T Pop(void);
void ClearStack(void);
//访问栈顶元素
T Peek(void) const;
//检测栈状态的方法
int StackEmpty(void) const;
};
template <class T>
stacknode<T> *lstack<T>::GetNode(const T& item,stacknode<T> *ptr)
{
stacknode<T> *temp;
temp=new stacknode<T>;
temp->data=item;
temp->next=ptr;
if(temp==NULL)
{
cerr<<"memory application fail"<<endl;
exit(1);
}
return temp;
}
template <class T>
lstack<T>::lstack(const lstack& stack)
{
stacknode<T> *ptr;
while(stack.head->next!=NULL)
{
Push(stack.head->data);
}
}
template <class T>
lstack<T>::~lstack(void)
{
stacknode<T> *ptr;
while(head!=NULL)
{
ptr=head;
head=head->next;
delete ptr;
}
top=-1;
}
template <class T>
void lstack<T>::Push(const T &item)
{
if(head==NULL)
{
head=GetNode(item);
top++;
}else
{
head=GetNode(item,head);
top++;
}
}
template <class T>
T lstack<T>::Pop(void)
{
if(top==-1)
{
cerr<<"Atempt to pop an empty stack!"<<endl;
exit(1);
}
T temp;
stacknode<T> *ptr;
temp=head->data;
ptr=head;
head = head->next;
delete ptr;
top--;
return(temp);
}
template <class T>
void lstack<T>::ClearStack(void)
{
stacknode<T> *ptr;
while(head!=NULL)
{
ptr=head;
head=head->next;
delete ptr;
}
top=-1;
}
template <class T>
T lstack<T>::Peek(void) const
{
if(top==-1)
{
cerr<<"Atempt to peek an empty stack!"<<endl;
exit(1);
}
T temp;
temp=head->data;
return(temp);
}
template <class T>
int lstack<T>::StackEmpty(void) const
{
return (top==-1);
}