Implement Stack using Queues/Implement Queue using Stacks

题目地址:https://leetcode.com/submissions/detail/88638615/https://leetcode.com/submissions/detail/88638372/

无论是用栈实现队列还是用队列实现栈,在Java中提供给了我们LinkedList这样一个容器,它的操作足以满足我们模拟队列与栈的操作。

队列模拟栈

public class ImplementStackUsingQueues {
    LinkedList queue = new LinkedList<>();

    // Push element x onto stack.
    public void push(int x) {
        queue.push(x);
    }

    // Removes the element on top of the stack.
    public void pop() {
        queue.pop();
    }

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

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

栈模拟队列:

public class ImplementQueueUsingStacks {
    LinkedList stack = new LinkedList<>();

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

    // 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.size() == 0 ? true : false;
    }

    @Override
    public String toString() {
        return stack.toString();
    }

    public static void main(String[] args) {
        ImplementQueueUsingStacks queue = new ImplementQueueUsingStacks();
        queue.push(1);
        queue.push(2);
        queue.push(3);
        queue.push(4);
        System.out.println(queue);
        System.out.println(queue.peek());
        queue.pop();
        System.out.println(queue.peek());
        System.out.println(queue.empty());
        queue.pop();
        System.out.println(queue);
    }
}

你可能感兴趣的:(Algorithm,Leetcode,Data,Structure)