1.选择顺序存储结构,定义一个空栈类,并定义入栈、出栈、取栈元素基本操作。然后在主程序中对给定的N个数据进行验证,输出各个操作结果。
<span style="font-size:14px;">#ifndef seqstack_H
#define seqstack_H
const int stacksize=20;
template<class T>
class seqstack
{
public:
seqstack();
~seqstack(){}
void push(T x);
T pop();
T gettop();
private:
T data[stacksize];
int top;
};
#endif
#include"seqstack.h"
template<class T>
seqstack<T>::seqstack()
{
top=-1;
}
template<class T>
void seqstack<T>::push(T x)
{
if(top==stacksize-1)throw"上溢";
top++;
data[top]=x;
}
template<class T>
T seqstack<T>::pop()
{
T x;
if(top==-1)throw"下溢";
x=data[top--];
return x;
}
template<class T>
T seqstack<T>::gettop()
{
if(top!=-1)
return data[top];
}
#include<iostream>
using namespace std;
#include"seqstack.cpp"
void main()
{
seqstack<int>S;
cout<<"对1、3、5和9执行入栈操作"<<endl;
S.push(1);
S.push(3);
S.push(5);
S.push(9);
cout<<"栈顶元素为:"<<S.gettop()<<endl;
cout<<"执行一次出栈操作"<<S.pop()<<endl;
cout<<"栈顶元素为:"<<S.gettop()<<endl;
}</span>
运行结果截图
2选择顺序存储结构,定义一个空栈队列,并定义入栈、出栈、取栈元素基本操作。然后在主程序中对给定的N个数据进行验证,输出各个操作结果。
<span style="font-size:14px;">#ifndef seqqueue_H
#define seqqueue_H
const int queuesize=100;
template<class T>
class seqqueue
{
public:
seqqueue();
~seqqueue(){}
void push(T x);
T pop();
T gettop();
private:
T data[queuesize];
int front,rear;
};
#endif
#include"seqqueue.h"
template<class T>
seqqueue<T>::seqqueue()
{
rear=front=queuesize-1;
}
template<class T>
void seqqueue<T>::push(T x)
{
if((rear+1)%queuesize==front)throw"上溢";
rear=(rear+1)%queuesize;
data[rear]=x;
}
template<class T>
T seqqueue<T>::pop()
{
if(rear=front)throw"下溢";
front=(front+1)%queuesize;
return data[front];
}
template<class T>
T seqqueue<T>::gettop()
{
int i;
if(rear=front)throw"下溢";
i=(front+1)%queuesize;
return data[i];
}
#include<iostream>
using namespace std;
#include"seqqueue.cpp"
void main()
{
seqqueue<int>S;
cout<<"对1、3、5和9执行入列操作"<<endl;
S.push(1);
S.push(3);
S.push(5);
S.push(9);
cout<<"执行一次出队操作"<<S.pop()<<endl;
cout<<"队头元素为:"<<S.gettop()<<endl;
}</span>
我写的是循环队列 不过不知道为什么 编译没有错误 运行后老出错 调试也找不出原因
希望老师有空可以帮我看看~~