一、顺序栈的实现:
#include<iostream>
using namespace std;
#include "SeqStack.cpp"
void main()
{
SeqStack<int> S;
if(S.Empty())
cout<<"栈为空"<<endl;
else
cout<<"栈非空"<<endl;
cout<<"对15和10执行入栈操作"<<endl;
S.Push(15);
S.Push(10);
cout<<"栈顶元素为:"<<endl;
cout<<S.GetTop()<<endl;
cout<<"执行一次出栈操作"<<endl;
S.Pop();
cout<<"栈顶元素为:"<<endl;
cout<<S.GetTop()<<endl;
}
#include"SeqStack.h"
template<class DataType>
SeqStack<DataType>::SeqStack()
{
top=-1;
}
template<class DataType>
void SeqStack<DataType>::Push(DataType x)
{
if(top==StackSize-1) throw"上溢";
top++;
data[top]=x;
}
template<class DataType>
DataType SeqStack<DataType>::Pop()
{
DataType x;
if(top==-1) throw"下溢";
x=data[top--];
return x;
}
template<class DataType>
DataType SeqStack<DataType>::GetTop()
{
if(top!=-1)
return data[top];
}
template<class DataType>
int SeqStack<DataType>::Empty()
{
if(top==-1)return 1;
else return 0;
}
#include"SeqStack.h" template<class DataType> SeqStack<DataType>::SeqStack() { top=-1; } template<class DataType> void SeqStack<DataType>::Push(DataType x) { if(top==StackSize-1) throw"上溢"; top++; data[top]=x; } template<class DataType> DataType SeqStack<DataType>::Pop() { DataType x; if(top==-1) throw"下溢"; x=data[top--]; return x; } template<class DataType> DataType SeqStack<DataType>::GetTop() { if(top!=-1) return data[top]; } template<class DataType> int SeqStack<DataType>::Empty() { if(top==-1)return 1; else return 0; }
二、链栈的实现
#ifndef LinkStack
#define LinkStack
typedef int dataType;
struct node
{
dataType data;
node *next;
};
class ls
{
public:
ls();
~ls();
void push(dataType var);
void pop(); dataType stackTop();
bool isEmpty();
private:
node *top; };
#endif
#include <iostream>
#include "LinkStack.h"
using namespace std;
ls::ls()
{
top = NULL;
}
ls::~ls()
{
node *ptr = NULL;
while(top != NULL)
{
ptr = top->next;
delete top;
top = ptr;
}
}
void ls::push(dataType var)
{
node *ptr = new node;
ptr->data = var;
ptr->next = top;
top = ptr;
}
void ls::pop()
{
node *ptr = top->next;
delete top;
top = ptr;
}
dataType ls::stackTop()
{
return top->data;
}
bool ls::isEmpty()
{
return top == NULL;
}
#include <iostream>
#include "LinkStack.h"
using namespace std;
int main()
{
ls l;
cout<<"对15和10 进行入栈操作"<<endl;
l.push(15);
l.push(10);
cout<<"执行一次出栈从操作"<<endl;
l.pop();
return 0;
}