本文參考自《劍指offer》一書,代碼采用Java語言。
題目
用兩個棧實現一個隊列。隊列的聲明如下,請實現它的兩個函數appendTail和deleteHead,分別完成在隊列尾部插入結點和在隊列頭部刪除結點的功能。
思路
這道題較簡單,自己先試着模擬一下插入刪除的過程(在草稿紙上動手畫一下):插入肯定是往一個棧stack1中一直插入;刪除時,直接出棧無法實現隊列的先進先出規則,這時需要將元素從stack1出棧,壓到另一個棧stack2中,然后再從stack2中出棧就OK了。需要稍微注意的是:當stack2中還有元素,stack1中的元素不能壓進來;當stack2中沒元素時,stack1中的所有元素都必須壓入stack2中。否則順序就會被打亂。
測試用例
1.往空隊列添加刪除元素
2.往非空隊列添加刪除元素
3.刪除至隊列為空
完整Java代碼
(含測試代碼)
import java.util.Stack; /** * * @Description 用兩個棧實現隊列 * * @author yongh * @date 2018年9月13日 下午2:17:22 */ // 題目:用兩個棧實現一個隊列。隊列的聲明如下,請實現它的兩個函數appendTail // 和deleteHead,分別完成在隊列尾部插入結點和在隊列頭部刪除結點的功能。 public class QueueWithTwoStacks { class Queue{ Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); /** * 插入結點 */ public void push(int node) { stack1.push(node); } /** * 刪除結點 */ public int pop() { if (stack2.empty()) { if (stack1.empty()) throw new RuntimeException("隊列為空!"); else { while (!stack1.empty()) stack2.push(stack1.pop()); } } return stack2.pop(); } } //=======測試代碼========== public void test1() { Queue queue= new Queue(); queue.push(1); queue.push(2); System.out.println(queue.pop()); queue.push(3); System.out.println(queue.pop()); System.out.println(queue.pop()); } /** * 往空隊列刪除元素 */ public void test2() { Queue queue= new Queue(); System.out.println(queue.pop()); } public static void main(String[] args) { QueueWithTwoStacks demo = new QueueWithTwoStacks(); demo.test1(); demo.test2(); } }

1 2 3 Exception in thread "main" java.lang.RuntimeException: 隊列為空!
收獲
1.學會用畫圖將抽象問題形象化