LeetCode Implement Queue using Stacks

来源:互联网 发布:数据降维方法 编辑:程序博客网 时间:2024/05/01 20:52

Description:

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.

Solution:

和MyStack一样的做法。

import java.util.*;class MyQueue {Stack<Integer> stack = new Stack<Integer>();// Push element x to the back of queue.public void push(int x) {Stack<Integer> temp = new Stack<Integer>();while (!stack.isEmpty())temp.push(stack.pop());stack.push(x);while (!temp.isEmpty())stack.push(temp.pop());}// Removes the element from in front of queue.public void pop() {stack.pop();}// Get the front element.public int peek() {return stack.peek();}// Return whether the queue is empty.public boolean empty() {return stack.isEmpty();}}


0 0
原创粉丝点击