本文主要是介绍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<Integer> 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<Integer> 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;}@Overridepublic 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);}
}
这篇关于Implement Stack using Queues/Implement Queue using Stacks的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!