#include "stdafx.h"
#include <iostream>
using namespace std;
//用栈模拟队列
class Data{
public:
Data():data(0),next(NULL){}
Data(int i):data(i),next(NULL){}
int data;
Data *next;
};
class Stack{
public:
Stack():Top(NULL){}
void Push(Data i);
void Pop(Data &d);
bool IsEmpty();
void Print();
private:
Data *Top;
};
//进栈
void Stack::Push(Data d){
Data *p=new Data(d.data);
if (IsEmpty()){ //如果栈为空
Top=p;
}else{ //新节点成为栈顶节点
p->next=Top;
Top=p;
}
}
//出栈
void Stack::Pop(Data &s){
if (IsEmpty()){//如果为空栈
cout<<"Stack Empty!"<<endl;
getchar();
exit(1);
}else{
s.data=Top->data;
Top=Top->next;
}
}
//判断是否为空
bool Stack::IsEmpty(){
if (Top==NULL){
return 1;
}
else
return 0;
}
//打印
void Stack::Print(){
Data *p=Top;
while (p!=NULL){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
class Queue{
public:
void enqueue(Data d); //入队
void dequeue(Data &d); //出队
bool IsEmpty();//是否为空
private:
Stack s1;//用于入队
Stack s2;//用于出队
};
//入队
void Queue::enqueue(Data d){
s1.Push(d);//只对s1进行进栈操作
}
//出队
void Queue::dequeue(Data &d){
Data temp(0);//局部变量,用于临时存储
if (s2.IsEmpty())//如果s2为空,把s1的所有元素push到s2中
while (!s1.IsEmpty()){
s1.Pop(temp); //弹出s1的元素
s2.Push(temp);//压入s2中
}
if(!s2.IsEmpty()){ //如果s2不为空
//此时如果s2不为空,弹出s2的栈顶元素
s2.Pop(d);
}
}
//队列判空
bool Queue::IsEmpty(){
//如果两个栈都为空,则返回1,否则返回0
if (s1.IsEmpty() && s2.IsEmpty()){
return 1;
}
else
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
Data data(0);//定义一个节点
Queue q;
q.enqueue(Data(1));
q.enqueue(Data(2));
q.enqueue(Data(3));
q.dequeue(data);
cout<<"dequeue "<<data.data<<endl;
q.enqueue(Data(4));
q.dequeue(data);
cout<<"dequeue "<<data.data<<endl;
q.dequeue(data);
cout<<"dequeue "<<data.data<<endl;
cout<<"IsEmpty "<<q.IsEmpty()<<endl;
q.dequeue(data);
cout<<"dequeue "<<data.data<<endl;
cout<<"IsEmpty "<<q.IsEmpty()<<endl;
system("pause");
return 0;
}
【笔面大全】使用两个栈模拟队列
最新推荐文章于 2022-09-11 11:56:40 发布