用栈来实现队列时,采用两个栈:一个用于入队列,一个用于出队列。
Queue{
Stack enStack;
Stack deStack;
}
当有元素入队列时,插入enStack的栈定;当有元素出队列时,检查deStack是否为空,如果为空则先把栈enStack的全部元素依次放入deStack;然后和deStack不为空的情况一样,删除deStack栈顶的元素。
vc6.0的源代码:
#include <iostream>
using namespace std;
class Stack{
public:
class Node{
public:
int data;
Node *next;
Node *pre;
Node(int d):data(d), next(0), pre(0){}
};
Stack():top(0),bottom(0){}
void push(int num){
Node *newNodePtr = new Node(num);
if (top == NULL)
{
top = newNodePtr;
bottom = newNodePtr;
}else{
newNodePtr->pre = top;
top->next = newNodePtr;
top = newNodePtr;
}
}
int pop(){
if (top == NULL){
return -1;
}
Node *delNodePtr = top;
top = top->pre;
if (top == NULL)
bottom = NULL;
int ret = delNodePtr->data;
delete delNodePtr;
return ret;
}
bool empty(){
if (top == NULL && bottom == NULL)
return true;
else
return false;
}
void displayTop2Bottom(){
Node *cur = top;
while (cur)
{
cout << cur->data << " ";
cur = cur->pre;
}
}
void displayBottom2Top(){
Node *cur = bottom;
while (cur)
{
cout << cur->data << " ";
cur = cur->next;
}
}
private:
Node *top;
Node *bottom;
};
class Queue{
public:
void enQueue(int num){
stackA.push(num);
}
void deQueue(){
if (stackB.empty())
{
while (stackA.empty() == false)
{
int num = stackA.pop();
stackB.push(num);
}
}
int ret = stackB.pop();
cout << "deQueue: " << ret << endl;
}
void display(){
if (!stackB.empty())
stackB.displayTop2Bottom();
if (!stackA.empty())
stackA.displayBottom2Top();
cout << endl;
}
private:
Stack stackA;
Stack stackB;
};
void main(){
Queue queue;
for (int i = 1; i <= 5; i ++)
queue.enQueue(i);
queue.display();
queue.deQueue();
queue.display();
queue.deQueue();
queue.display();
queue.enQueue(6);
queue.enQueue(7);
queue.enQueue(8);
queue.display();
}
来自于http://hi.baidu.com/xiangzifengshi/blog/item/e26c173054678a365ab5f530.html