Implement Stack by Two Queues (Ladder)

Description

Implement a stack by two queues. The queue is first in first out (FIFO). That means you can not directly pop the last element in a queue.

Example

push(1)
pop()
push(2)
isEmpty() // return false
top() // return 2
pop()
isEmpty() // return true

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
    class Stack {
    public:
     void Movedata() {
         while (q1.size() > 1) {
             int tmp = q1.front();
             q1.pop();
             q2.push(tmp);
         }
         return;
     }
     void swapqueue () {
         queue<int> tmp(q1);
         q1 = q2;
         q2 = tmp;
         return;
     }
     // Push a new item into the stack
     void push(int x) {
         // Write your code here
         q1.push(x);
         return;
     }
     // Pop the top of the stack
     void pop() {
         // Write your code here
         Movedata();
         q1.pop();
         swapqueue();
         return;
     }
     // Return the top of the stack
     int top() {
         // Write your code here
         Movedata();
         int result = q1.front();
         q1.pop();
         q2.push(result);
         swapqueue();
         return result;
     }
     // Check the stack is empty or not.
     bool isEmpty() {
         // Write your code here
         return q1.empty();
     }
     queue<int> q1;
     queue<int> q2;
    };
    

Similar problems

x

Tags

x

results matching ""

    No results matching ""