每个程序分为三个文件,分别用来定义类(.h)、实现类(.cpp)、main函数测试(main.cpp)
一、顺序栈
可根据需要自行修改main文件中的测试程序
//Seqstack.h
const int N=10;
template<class T>
class Seqstack
{
private:
T data[N];
int top;
public:
Seqstack();
~Seqstack();
T pop();
void push(T x);
T gettop();
bool empty();
};
//Seqstack.cpp
#include<iostream>
using namespace std;
#include"Seqstack.h"
template <class T>
Seqstack<T>::Seqstack()
{
top=-1;
}
template<class T>
Seqstack<T>::~Seqstack(){}
template<class T>
void Seqstack<T>::push(T x)
{
if(top==N-1) throw"上溢";
top++;
data[top]=x;
}
template<class T>
T Seqstack<T>::pop()
{
if(top==-1) throw"下溢";
return data[top--];
}
template<class T>
T Seqstack<T>::gettop()
{
if(top!=-1)
return data[top];
}
template<class T>
bool Seqstack<T>::empty()
{
if(top==-1) return 1;
else return 0;
}
//Seqstackmain.cpp
#include<iostream>
#include"Seqstack.cpp"
using namespace std;
int main()
{
Seqstack<int> s;
if(s.empty()) cout<<"栈是空的"<<endl;
else cout<<"栈是非空的"<<endl;
cout<<"请输入要插入的N个数据:"<<endl;
int a[N];
for(int i=0;i<N;i++) cin>>a[i];
for(int i=0;i<N;i++)
{
s.push(a[i]);
}
cout<<"入栈完毕,显示栈顶数据:"<<endl;
cout<<s.gettop()<<endl;
cout<<"依次出栈:"<<endl;
while(!s.empty())
{
cout<<s.pop()<<" ";
}
cout<<endl;
if(s.empty()) cout<<"栈是空的"<<endl;
else cout<<"栈是非空的"<<endl;
s.~Seqstack();
return 0;
}
二、顺序队列
//Seqqueue.h
const int N = 10;
template<class T>
class Seqqueue
{
private:
T data[N];
int head;
int tail;
public:
Seqqueue();
~Seqqueue();
void push(T x);
bool empty();
bool full();
T pop();
T front();
};
//Seqqueue.cpp
#include<iostream>
#include"Seqqueue.h"
using namespace std;
template<class T>
Seqqueue<T>::Seqqueue()
{
head=-1;
tail=-1;
}
template<class T>
Seqqueue<T>::~Seqqueue(){}
template<class T>
void Seqqueue<T>::push(T x)
{
if(tail==N) throw"上溢";
data[tail++]=x;
}
template<class T>
T Seqqueue<T>::pop()
{
if(head==N) throw"下溢";
return data[head++];
}
template<class T>
T Seqqueue<T>::front()
{
return data[head];
}
template<class T>
bool Seqqueue<T>::empty()
{
if(tail==-1 || head==N-1) return 1;
else return 0;
}
template<class T>
bool Seqqueue<T>::full()
{
if(tail==N) return 1;
else return 0;
}
//Seqqueuemain.cpp
#include<iostream>
#include"Seqqueue.cpp"
using namespace std;
int main()
{
Seqqueue<int> s;
if(s.empty()) cout<<"队列是空的"<<endl;
else cout<<"队列是非空的"<<endl;
cout<<endl<<"请输入要插入的N个数据:"<<endl;
int a[N];
for(int i=0;i<N;i++) cin>>a[i];
cout<<endl<<"执行入队操作"<<endl;
for(int i=0;i<N;i++)
{
s.push(a[i]);
}
if(s.full()) cout<<endl<<"队列是非满的"<<endl;
else cout<<endl<<"队列是满的"<<endl;
cout<<endl<<"当前队头元素为:"<<endl;
cout<<s.front()<<endl;
cout<<endl<<"依次执行出队操作:"<<endl;
while(!s.empty())
{
cout<<s.pop()<<" ";
}
cout<<endl;
if(s.empty()) cout<<endl<<"队列是空的"<<endl;
else cout<<endl<<"队列是非空的"<<endl;
s.~Seqqueue();
return 0;
}