1.顺序栈的实现
#include <cstdlib>
#include <iostream>
using namespace std;
template <class Type>
class MStack
{
private:
int top,max;
Type *stack;
public:
MStack(int m):max(m)
{
stack=new Type(max);
top=-1;
}
~MStack()
{
delete[] stack;
}
inline bool Add(const Type item)
{
if(StackFull())
{
cout<<"stack is full!\n";
return false;
}
else
{
stack[++top]=item;
return true;
}
}
inline bool Del(Type &item)
{
if(StackEmpty())
{
cout<<"stack is empty!\n";
return false;
}
else
{
item=stack[top--];
return true;
}
}
inline bool StackEmpty()
{
if(top<0)
return true;
else
return false;
}
inline bool StackFull()
{
if(top>=(max-1))
return true;
else
return false;
}
};
int main(int argc, char *argv[])
{
MStack<int> *s=new MStack<int>(10);
s->Add(3);
s->Add(5);
int i=0;
s->Del(i);
cout<<i<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}
2.链式栈的实现
#include <cstdlib>
#include <iostream>
using namespace std;
template <class Type>
class LinkedStack
{
private:
struct node
{
Type data;
struct node *link;
};
struct node *top;
int length;
public:
LinkedStack()
{
top=NULL;
length=0;
}
~LinkedStack()
{
struct node *temp;
while(top)
{
temp=top;
top=top->link;
delete temp;
}
}
inline bool Add(const Type item)
{
node *t=new node;
if(t)
{
t->data=item;
t->link=top;
top=t;
length++;
return true;
}
else
{
cout<<"out of space!"<<endl;
return false;
}
}
inline bool Del(Type &item)
{
if(StackEmpty())
{
cout<<"stack is empty!\n";
return false;
}
else
{
struct node *t;
item=top->data;
t=top;
top=top->link;
delete t;
length--;
return true;
}
}
inline bool StackEmpty()
{
if(top==NULL)
return true;
else
return false;
}
inline int GetLength()
{return length;}
};
int main(int argc, char *argv[])
{
LinkedStack<int> *s=new LinkedStack<int>();
s->Add(3);
cout<<s->GetLength()<<endl;
s->Add(5);
cout<<s->GetLength()<<endl;
int i=0;
s->Del(i);
cout<<i<<endl;
system("PAUSE");
return EXIT_SUCCESS;
}