栈:
栈:限定仅在表尾进行插入和删除操作的线性表。
允许插入和删除的一端称为栈顶,另一端称为栈底。
#include<iostream>
using namespace std;
const int MAX_SIZE=100;
template <class T>
class seqStack
{
public:
seqStack(){};
~seqStack(){};
void Push(T x);//入栈
T Pop();//出栈
T GetTop();//得到栈顶元素,但不出栈
bool Empty();//判断栈是否为空
private:
T data[MAX_SIZE];
int top;
};
template <class T>
void seqStack<T>::Push ( T x)
{
if (top==MAX_SIZE-1)
cout<<"栈满"<<endl;
else{
top++;
data[top]=x;
}
}
template <class T>
bool seqStack<T>::Empty ()
{
if (top==-1)
return true;
return false;
}
template <class T>
T seqStack<T>::GetTop ( )
{
if (Empty())
cout<<"栈空"<<endl;
else
return data[top];
}
template <class T>
T seqStack<T>:: Pop ( )
{
if (top==-1)
cout<<"栈空"<<endl;
else
{
T x=data[top];
top--;
return x;
}
}
int main()
{
seqStack<int> s;
for(int i=0;i<3;i++){
int x;
cin>>x;
s.Push(x);
}
cout<<s.Empty()<<endl;
cout<<s.GetTop()<<endl;
cout<<s.Pop()<<endl;
}
队列:只允许在一端进行插入操作,而另一端进行删除操作的线性表。
允许插入(也称入队、进队)的一端称为队尾,允许删除(也称出队)的一端称为队头。
#include <bits/stdc++.h>
using namespace std;
template<typename T>
struct Node
{
T data;
Node<T> *next;
};
template <class T>
class LinkQueue
{
public:
LinkQueue();//构造
~LinkQueue();//析构
void EnQueue(T x);//入队
T DeQueue();//出队
void PrintQueue();//遍历
private:
Node<T> *front, *rear;
};
template <class T>
LinkQueue<T>::LinkQueue()//构造
{
front=new Node<T>;
front->next=NULL;
rear=front;
}
template<class T>
LinkQueue<T>::~LinkQueue()//
{
Node<T> *q;
while(front)
{
q=front->next;
delete front;
front=q;
}
}
template <class T>
void LinkQueue<T>::EnQueue(T x)//入队
{
Node<T> *s;
s=new Node<T>;
s->data=x;
s->next=NULL;
rear->next=s;
rear=s;
}
template <class T>
T LinkQueue<T>::DeQueue()//出队
{
Node<T> *p;
if(rear==front)
return 0;
p=front->next;
T x=p->data;
front->next=p->next;
delete p;
if(front->next==NULL)
rear=front;
//return x;
}
template<class T>
void LinkQueue<T>::PrintQueue()
{
Node<T> *p;
p=front->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int main()
{
LinkQueue<int> link;
int y;
while(cin>>y)
{
if(y==-3)
break;
if(y>=10&&y<=99)
{
link.EnQueue(y);
}
if(y==-1)
{
link.DeQueue();
}
if(y==-2)
{
link.PrintQueue();
}
}
return 0;
}