225 用队列实现栈 java

参考自: https://github.com/awangdev/LintCode/edit/master/Java/Implement%20Stack%20using%20Queues.java

代码及测试案例:

使队列queue1中最新存入的元素始终在队列front,这样可以保证后进先出。实现栈的功能。

后面附了几种方法,测试都是可以用的。

package com.company;


import java.util.LinkedList;
import java.util.Queue;

 public class TwoQueueImplStack {
     Queue<Integer> queue1;
     Queue<Integer> queue2;

     /**
      * Initialize your data structure here.
      */
     public TwoQueueImplStack() {
         queue1 = new LinkedList<>();
         queue2 = new LinkedList<>();
     }

     /**
      * Push element x onto stack.
      */
     public void push(int x) {
         queue2 = queue1;
         queue1 = new LinkedList<>();//q1留空,目的是每次新加入的元素都在q1队列的front
         queue1.offer(x);//q1的front加入x
         while (!queue2.isEmpty()) {
             queue1.offer(queue2.poll());
         }
     }

     /**
      * Removes the element on top of the stack and returns that element.
      */
     public int pop() {
         return queue1.poll();
     }

     /**
      * Get the top element.
      */
     public int top() {
         return queue1.peek();
     }

     /**
      * Returns whether the stack is empty.
      */
     public boolean empty() {
         return queue1.isEmpty();
     }




    public static void main(String[] args) {
        TwoQueueImplStack qs = new TwoQueueImplStack();
        qs.push(2);
        qs.push(4);
        qs.push(7);
        qs.push(5);
        System.out.println(qs.pop());
        System.out.println(qs.pop());

        qs.push(1);
        System.out.println(qs.pop());

    }

}

E
1525667621
tags: Stack, Design

如题.

#### Queue, 倒水
- 两个Queue,交互倒水
- 用一个Temp做swap

##### 做法1
- 逻辑在push里面:
- 1. x 放q2。
- 2. q1全部offer/append到q2.
- 3. 用一个Temp做swap q1, q2.
- q1的头,就一直是最后加进去的值.


##### 做法2
- 逻辑在top()/pop()里, 每次换水,查看末尾项.


```
/*
LeetCode:
Implement the following operations of a stack using queues.

push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty.

Notes:
You must use only standard operations of a queue -- 
which means only push to back, peek/pop from front, size, and is empty operations are valid.

Depending on your language, queue may not be supported natively. 
You may simulate a queue by using a list or deque (double-ended queue), 
as long as you use only standard operations of a queue.

You may assume that all operations are valid 
(for example, no pop or top operations will be called on an empty stack).
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.
*/

class MyStack {
    Queue<Integer> queue;
    Queue<Integer> tempQueue;
    /** Initialize your data structure here. */
    public MyStack() {
        queue = new LinkedList<>();
        tempQueue = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        tempQueue = queue;
        queue = new LinkedList<>();
        queue.offer(x);
        while (!tempQueue.isEmpty()) {
            queue.offer(tempQueue.poll());
        }
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return queue.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.isEmpty();
    }
}


/*
Thoughts:
1. When top()/pop() on the queue, we need to consume all the items on that queue first, 
then return the last item.
2. Need to save the consumed items back to the queue.
*/
class MyStack {
    private Queue<Integer> queue;
    private Queue<Integer> tempQueue;

    /** Initialize your data structure here. */
    public MyStack() {
        queue = new LinkedList<>();
        tempQueue = new LinkedList<>();
    }
    
    /** Find the top and backfill queue with all consumed items */
    private int findTop() {
        while (queue.size() > 1) {
            tempQueue.offer(queue.poll());
        }
        int num = queue.poll();
        queue = tempQueue;
        tempQueue = new LinkedList<>();
        return num;
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        queue.offer(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return findTop();
    }
    
    /** Get the top element. */
    public int top() {
        int num = findTop();
        queue.offer(num);
        return num;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */


/*
LintCode:
Implement Stack by Two Queues

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.

Have you met this question in a real interview? Yes
Example
push(1)
pop()
push(2)
isEmpty() // return false
top() // return 2
pop()
isEmpty() // return true
Tags Expand 
Stack Queue

*/

/*
    Thoughts:
    2 queue are like two cups. We are fliping water into/out between q1 and q2.
    pop and top are fliping water.
    Use p1 as the base.
*/

class Stack {
    private Queue<Integer> q1 = new LinkedList<Integer>();
    private Queue<Integer> q2 = new LinkedList<Integer>();
    // Push a new item into the stack
    public void push(int x) {
        q1.offer(x);
    }

    // Pop the top of the stack
    public void pop() {
           while (q1.size() > 1) {
               q2.offer(q1.poll());
           }
           q1.poll();
           swap();
    }

    // Return the top of the stack
    public int top() {
           while (q1.size() > 1) {
               q2.offer(q1.poll());
           }
           int rst = q1.poll();
           q2.offer(rst);
           swap();
           return rst;
    }

    public void swap(){
        Queue<Integer> temp = q1;
           q1 = q2;
           q2 = temp;
    }

    // Check the stack is empty or not.
    public boolean isEmpty() {
        return q1.isEmpty();
    }    
}
```

另一段代码比较:

package com.company;


import java.util.ArrayDeque;
import java.util.Queue;

 public class TwoQueueImplStack {
    Queue<Integer> queue1 = new ArrayDeque<Integer>();
    Queue<Integer> queue2 = new ArrayDeque<Integer>();

    /*
     * 向栈中压入数据
     */
    public void push(Integer element){
        //两个队列都为空时,优先考虑 queue1
        if(queue1.isEmpty() && queue2.isEmpty()){
            queue1.add(element);
            return;
        }

        //如果queue1为空,queue2有数据,直接放入queue2
        if(queue1.isEmpty()){
            queue2.add(element);
            return;
        }

        //如果queue2为空,queue1有数据,直接放入queue1中
        if(queue2.isEmpty()){
            queue1.add(element);
            return;
        }
    }

    /*
     * 从栈中弹出一个数据
     */
    public Integer pop(){
        //如果两个栈都为空,则没有元素可以弹出,异常
        if(queue1.isEmpty() && queue2.isEmpty()){
            try{
                throw new Exception("satck is empty!");
            }catch(Exception e){
                e.printStackTrace();
            }
        }

        //如果queue1中没有元素,queue2中有元素,将其queue2中的元素依次放入queue1中,直到最后一个元素,弹出即可
        if(queue1.isEmpty()){
            while(queue2.size() > 1){
                queue1.add(queue2.poll());
            }
            return queue2.poll();
        }

        //如果queue2中没有元素,queue1中有元素,将其queue1中的元素依次放入queue2中,直到最后一个元素,弹出即可
        if(queue2.isEmpty()){
            while(queue1.size() > 1){
                queue2.add(queue1.poll());
            }
            return queue1.poll();
        }

        return (Integer)null;
    }
    public static void main(String[] args) {
        TwoQueueImplStack qs = new TwoQueueImplStack();
        qs.push(2);
        qs.push(4);
        qs.push(7);
        qs.push(5);
        System.out.println(qs.pop());
        System.out.println(qs.pop());

        qs.push(1);
        System.out.println(qs.pop());

    }

}

猜你喜欢

转载自blog.csdn.net/nsjlive/article/details/82632605