用栈来实现队列

用栈来实现队列时,采用两个栈:一个用于入队列,一个用于出队列。

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();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值