用栈实现队列和用队列实现栈
生活随笔
收集整理的這篇文章主要介紹了
用栈实现队列和用队列实现栈
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先需要使用上篇文章(用數組實現棧和隊列)中的棧和隊列兩個類
1.棧實現隊列:思路是有兩個棧,一個用來放數據(數據棧),一個用來輔助(輔助棧)。數據添加時,會依次壓人棧,取數據時肯定會取棧頂元素,但我們想模擬隊列的先進先出,所以就得取棧底元素,那么輔助棧就派上用場了,把數據棧的元素依次彈出到輔助棧,但保留最后一個元素,最后數據棧就剩下了最后一個元素,直接把元素返回,這時數據棧已經沒有了數據。最后呢,把輔助棧的元素依次壓人數據棧,這樣,我們成功取到了棧底元素。
代碼如下:
package com.sxt.test.java;public class Stack2Queue {/*** 用棧的入棧和出棧* 來實現隊列的入隊和出隊* stack1是入棧的,stack2是出棧的。入隊列:直接壓入stack1即可出隊列:如果stack2不為空,把stack2中的棧頂元素直接彈出;否則,把stack1的所有元素全部彈出壓入stack2中,再彈出stack2的棧頂元素* */Stack stack1 = new Stack();Stack stack2 = new Stack();public void add(Object o) {stack1.push(o);}public Object poll() {Object o = null;if(stack2.length()==0) {//把stack1的數據放入stack2,留下最后一個數據while(stack1.length()>1) {stack2.push(stack1.pop());}if(stack1.length()==1) {//把stack1的留下的那個數據返回出去o = stack1.pop();}}else {o = stack2.pop();}return o;}public int length() {return stack1.length()+stack2.length();}}?
2.隊列實現棧
思路同上:有數據隊列和輔助隊列,模擬棧的先進后出,隊列是隊尾進隊頭出,也就是說每次取值要取隊列的隊尾元素,數據隊列出隊到輔助隊列,留下最后一個元素返回,輔助隊列再把元素出隊到數據隊列
代碼如下:
package com.sxt.test.java;public class Queue2Stack {/*** 用隊列的入隊和出隊* 來實現棧的入棧和出棧* */Queue queue1 = new Queue();//主要存放數據Queue queue2 = new Queue();//輔助public void push(Object o) {queue1.add(o);}public Object pop() {Object o = null;while(queue1.length()>1) {queue2.add(queue1.poll());}if(queue1.length()==1) {o = queue1.poll();while(queue2.length()>0) {queue1.add(queue2.poll());}}return o;}public int length() {return queue1.length();}}?
3.測試類
/*** 用兩個棧實現隊列* */Stack2Queue stack2Queue = new Stack2Queue();stack2Queue.add("a");stack2Queue.add("b");stack2Queue.add("c");stack2Queue.add("d");stack2Queue.add("e");while(stack2Queue.length()>0) {System.out.println(stack2Queue.poll());}/*** 用兩個隊列實現棧* */Queue2Stack queue2Stack = new Queue2Stack();queue2Stack.push("a");queue2Stack.push("c");queue2Stack.pop();queue2Stack.push("d");queue2Stack.push("e");queue2Stack.push("f");queue2Stack.push("g");queue2Stack.push("h");while(queue2Stack.length()>0) {System.out.println(queue2Stack.pop());}?
轉載于:https://www.cnblogs.com/wwzyy/p/5507942.html
總結
以上是生活随笔為你收集整理的用栈实现队列和用队列实现栈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android Framework---
- 下一篇: ajax 载入html后不能执行其中的j