算法练习day8——190326(队列实现栈、栈实现队列)
生活随笔
收集整理的這篇文章主要介紹了
算法练习day8——190326(队列实现栈、栈实现队列)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.僅用隊列結構實現棧結構
1.1 分析:
1、所有數先入data隊列:
2、將前n-1個數入help隊列,彈出最后一個數:
3、將help中的前n-2個數入data隊列,彈出最后一個數:
4、重復2~3,即可按先入后出的順序彈出所有元素。
1.2 代碼實現
package Solution; import java.util.LinkedList; import java.util.Queue;class queueToStack{Queue<Integer> data;Queue<Integer> help;public queueToStack() {this.data=new LinkedList<Integer>();this.help=new LinkedList<Integer>();}public void push(int num) {data.add(num);}public Integer peek() {if (data.isEmpty()) {throw new RuntimeException("Stack is empty!");}while(data.size()>1)help.add(data.poll());int result=data.poll();help.add(result);//只返回不刪除swap();return result;}public Integer pop() {if (data.isEmpty()) {throw new RuntimeException("Stack is empty!");}while(data.size()>1)help.add(data.poll());int result=data.poll();//返回帶刪除swap();return result;}public boolean isEmpty() {return data.isEmpty();}public void swap() {//改變引用Queue<Integer> temp=data;data=help;help=temp;} }public class Queue_To_Stack {public static void main(String[] args) {queueToStack qts=new queueToStack();qts.push(1);qts.push(2);System.out.println(qts.pop());qts.push(3);System.out.println(qts.pop());System.out.println(qts.pop());qts.push(4);qts.push(5);System.out.println(qts.pop());} }運行結果:
注意:隊列的先入先出!!!
2.僅用棧結構實現隊列結構
2.1 分析
用兩個棧:push棧,pop棧
- push棧:用于入隊列
- pop棧:用于出隊列
兩種思想:
一種思想(倒的比較頻繁):
要入隊列時,都往push棧加;
出隊列時,將push棧中的數據倒入pop棧中,從pop棧頂彈出一個元素;然后將剩余數據倒回到push棧中。
另一種思想:
push往pop倒數據,需滿足:
2.2 代碼實現
package Solution;import java.util.Stack;class StackToQueue{Stack<Integer> pushStack;Stack<Integer> popStack;public StackToQueue(){this.pushStack=new Stack<Integer>();this.popStack=new Stack<Integer>();}public void push(int num) {pushStack.push(num);}public Integer peek() {if (pushStack.isEmpty()) {throw new RuntimeException("Queue is empty!");}while(!pushStack.isEmpty())popStack.push(pushStack.pop());int result=popStack.peek();while(!popStack.isEmpty())pushStack.push(popStack.pop());return result;}public Integer poll() {if (pushStack.isEmpty()) {throw new RuntimeException("Queue is empty!");}while(!pushStack.isEmpty())popStack.push(pushStack.pop());int result=popStack.pop();//彈出,少一個while(!popStack.isEmpty())pushStack.push(popStack.pop());return result;} } public class Stack_To_Queue {public static void main(String[] args) {StackToQueue stq=new StackToQueue();stq.push(1);stq.push(2);System.out.println(stq.poll());stq.push(3);System.out.println(stq.poll());System.out.println(stq.poll());stq.push(4);stq.push(5);System.out.println(stq.poll());} }運行結果:
?
總結
以上是生活随笔為你收集整理的算法练习day8——190326(队列实现栈、栈实现队列)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法练习day8——190326(猫狗队
- 下一篇: 算法练习day9——190327(“之”