[LeetCode][数据结构]Implement Queue using Stacks

来源:互联网 发布:淘宝登录页面改进建议 编辑:程序博客网 时间:2024/06/16 10:47

题目描述:

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.
思路:
前提:使用栈来实现队操作
过程:要区分清楚队和栈的区别,对于四种操作来说,判断是否为空是一样的,差别在于队是先进先出,栈是先进后出,队头元素是历史久远的元素,栈顶元素是小鲜肉元素。那插入时无需计较,保存在当前数据结构即可,关键是弹出和取队头元素时。想象一个动态的过程,一个栈中的元素,依次弹出放入另一个栈中即是队的顺序,所以我们可以借用两个栈,插入时按照栈的方式插入,在需要做取队头或弹出操作时,将当前栈中的元素弹出到另一个栈即可

代码实现:
class MyQueue {    Stack<Integer> queueS = new Stack<Integer>();    Stack<Integer> stackS = new Stack<Integer>();        // Push element x to the back of queue.    public void push(int x) {        stackS.push(x);    }    // Removes the element from in front of queue.    public void pop() {        if(!queueS.isEmpty()) queueS.pop();        else{            while(!stackS.isEmpty()) queueS.push(stackS.pop());            queueS.pop();        }    }    // Get the front element.    public int peek() {        if(!queueS.isEmpty()) return queueS.peek();        else{            while(!stackS.isEmpty()) queueS.push(stackS.pop());            return queueS.peek();        }    }    // Return whether the queue is empty.    public boolean empty() {        return stackS.isEmpty()&&queueS.isEmpty();    }}


0 0
原创粉丝点击