用栈实现队列与用队列实现栈
生活随笔
收集整理的這篇文章主要介紹了
用栈实现队列与用队列实现栈
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一.用棧實現隊列
用棧實現隊列的思路是用兩個棧,只是在出隊的時候,將第一個棧中的元素移動到另一個棧中,在從第二個棧中出棧就可以了.
import java.util.Stack;public class MyQueue {/*你只能使用標準的棧操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。*/private final Stack<Integer> stack1;private final Stack<Integer> stack2;public MyQueue() {stack1 = new Stack<>();stack2= new Stack<>();}public void push(int x) {stack1.push(x);}public int pop() {if(stack2.isEmpty()){moveS1toS2();}return stack2.pop();}public int peek() {if(stack2.isEmpty()){moveS1toS2();}return stack2.peek();}private void moveS1toS2(){while (!stack1.isEmpty()){stack2.push(stack1.pop());}}public boolean empty() {return stack1.empty() && stack2.empty();} }二.用一個隊列實現棧
用一個queue來存儲數據,用一個值來存儲棧頂元素.在出棧時,需要把n-2個元素重新出棧,然后加入隊列,剩下兩個元素,一個作為棧頂,一個作為方法返回.
import java.util.LinkedList; import java.util.Queue;public class MyStack {/*你只能使用隊列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 這些操作。*/private Queue<Integer> queue ;private int top=0;public MyStack() {queue = new LinkedList<>();}public void push(int x) {queue.offer(x);top = x;}public int pop() {int n=queue.size();while (n>2){queue.offer(queue.poll());n--;}top = queue.peek();queue.offer(queue.poll());return queue.poll();}public int top() {return top;}public boolean empty() {return queue.isEmpty();}}總結
以上是生活随笔為你收集整理的用栈实现队列与用队列实现栈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode-199二叉树的右视图(
- 下一篇: 【postgresql初始化失败】ini