[leetcode]Implement Queue using Stacks

这几天都在忙项目所以挑了一些不怎么费脑的脑子的题目练习

题目描述如下:

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..

Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.

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

You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

利用Stack来实现一个Queue,没有什么难点,就是在对首字母操作时需要建一个临时的Stack tmp来过渡一下即可,代码如下:

class MyQueue {

    Stack<Integer> stack;

    MyQueue(){
        stack = new Stack<Integer>();
    }

    // Push element x to the back of queue.
    public void push(int x) {
        stack.push(x);
    }

    // Removes the element from in front of queue.
    public void pop() {
        Stack<Integer> tmp = new Stack<Integer>();
        int data;
        while(stack.size() > 1){
            data = stack.peek();
            tmp.push(data);
            stack.pop();
        }
        stack.pop();
        while(!tmp.isEmpty()){
            data = tmp.peek();
            stack.push(data);
            tmp.pop();
        }
    }

    // Get the front element.
    public int peek() {
        Stack<Integer> tmp = new Stack<Integer>();
        int data, res;
        while(stack.size() > 1){
            data = stack.peek();
            tmp.push(data);
            stack.pop();
        }
        res = stack.peek();
        while(!tmp.isEmpty()){
            data = tmp.peek();
            stack.push(data);
            tmp.pop();
        }
        return res;
    }

    // Return whether the queue is empty.
    public boolean empty() {
        return stack.size() == 0;
    }
}

题目链接:https://leetcode.com/problems/implement-queue-using-stacks/

你可能感兴趣的:(LeetCode)