【Java】 劍指offer(8) 用兩個棧實現隊列

本文參考自《劍指offer》一書,代碼採用Java語言。html

 更多:《劍指Offer》Java實現合集 java

題目

  用兩個棧實現一個隊列。隊列的聲明以下,請實現它的兩個函數appendTail和deleteHead,分別完成在隊列尾部插入結點和在隊列頭部刪除結點的功能。node

思路

  這道題較簡單,本身先試着模擬一下插入刪除的過程(在草稿紙上動手畫一下):插入確定是往一個棧stack1中一直插入;刪除時,直接出棧沒法實現隊列的先進先出規則,這時須要將元素從stack1出棧,壓到另外一個棧stack2中,而後再從stack2中出棧就OK了。須要稍微注意的是:當stack2中還有元素,stack1中的元素不能壓進來;當stack2中沒元素時,stack1中的全部元素都必須壓入stack2中。不然順序就會被打亂。app

測試用例ide

  1.往空隊列添加刪除元素函數

  2.往非空隊列添加刪除元素post

  3.刪除至隊列爲空測試

完整Java代碼

(含測試代碼)url

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: 隊列爲空!
QueueWithTwoStacks

 

收穫

  1.學會用畫圖將抽象問題形象化spa

 

 更多:《劍指Offer》Java實現合集

相關文章
相關標籤/搜索