[Leetcode]225. 用队列实现栈 、剑指 Offer 09. 用两个栈实现队列

225. 用队列实现栈

如题

题解

在push时候搞点事情:push时入队1,在把队2的元素一个个入队1,再交换队2和队1,保持队1除pushguocheng 始终为空。

代码

class MyStack {
    private Queue<Integer> q1;
    private Queue<Integer> q2;

    /** Initialize your data structure here. */
    public MyStack() {
        q1=new LinkedList<>();
        q2=new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        q1.offer(x);
        while(!q2.isEmpty()){
            q1.offer(q2.poll());
        }
        Queue temp=q1;
        q1=q2;
        q2=temp;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return q2.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return q2.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return q2.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();
 */

剑指 Offer 09. 用两个栈实现队列

题解

入队直接入栈1
出队:若栈2有元素直接出栈,否则若栈1为空则返回-1,若不为空则全部入栈2并弹出栈顶元素。

代码

class CQueue {
LinkedList s1,s2;
public CQueue() {
s1 = new LinkedList<>();
s2 = new LinkedList<>();
}

public void appendTail(int value) {
    s1.add(value);
}

public int deleteHead() {
    if(!s2.isEmpty()){
        return s2.removeLast();
    }else if(s1.isEmpty()){
        return -1;
    }else{
        while(!s1.isEmpty()){
            int val=s1.removeLast();
            s2.add(val);
        }
        return s2.removeLast();
    }
}

}

/**

  • Your CQueue object will be instantiated and called as such:
  • CQueue obj = new CQueue();
  • obj.appendTail(value);
  • int param_2 = obj.deleteHead();
    */

posted on 2020-06-23 00:22  coding_gaga  阅读(67)  评论(0编辑  收藏  举报

导航