每天一道算法題——用棧實現隊列

這道題也是我面試中的一道題,但是這道題答的也不是很好,今天就來總結這道題所用的算法吧。首先,用兩個棧實現隊列:
由於之前對數據結構和算法不是很瞭解,只是知道棧是LIFO,隊列是FIFO,當被問到的時候思考了半天,想出來一個不是很巧妙的算法:設置兩個棧分別爲stack1,stack2,入隊操作我想的就是將數據壓入到stack1中,而出隊操作就是將pop出stack1中所有元素,並將它們push到stack二中,這樣順序就倒回來了。然後彈出棧頂元素,再將stack2中的元素出棧,壓入到stack1中。這樣來回入隊,出對比較繁瑣。
優化算法:
入隊在stack1中進行,出隊在stack2中進行。
入隊:直接把元素壓入stack1中。

出隊:如果stack2不爲空,每次都彈出棧頂元素;如果stack2爲空,就將stack1中所有元素倒入stack2中,然後彈出stack2中的棧頂元素。若兩個棧都爲空,則無法出隊


下面是代碼實現過程:
package p_13_stack2queue;

import java.util.Stack;

public class Stack2Queue {

	private Stack stack1, stack2;
	private int maxLength = 0;
	
	public Stack2Queue(int capacity) {
		this.maxLength = capacity;
		stack1 = new Stack();
		stack2 = new Stack();
	}
	
	public boolean push(int item) {
		//if(stack1.isEmpty() || stack1.size()>maxLength) {
		if(stack1.size()>maxLength) {
			return false;
		}
		stack1.push(item);
		return true;
	}
	
	public int pop(){
//		if(stack1.isEmpty() && stack2.isEmpty()){
//			return -1;
//		}
		if(stack2.isEmpty()) {
			if(stack1.isEmpty()) {
				return -1;
			}else {
				while(!stack1.isEmpty()){
					stack2.push(stack1.pop());
				}
				return (int) stack2.pop();
			}
		}
		/*if(!stack2.isEmpty()){
			return (int)stack2.pop();
		}else{
			while(!stack1.isEmpty()){
				stack2.push(stack1.pop());
			}
			return (int)stack2.pop();
		}*/
		//stack2.pop();
		return (int)stack2.pop();
	}
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Stack2Queue queue =  new Stack2Queue(5);
		queue.push(1);
		queue.push(2);
		System.out.println(queue.pop());
		queue.push(3);
		System.out.println(queue.pop());
		System.out.println(queue.pop());
	}

}
第二個我們來看看怎麼使兩個隊列實現棧:
出入棧都在queue1完成,而將queue2作爲一箇中轉。
入棧:直接壓入queue1中
出棧:將queue1除最後一個元素外的 所有元素倒入queue1中,再將queue1中的元素出隊,再把queue2中的元素到會queue1中。
優化方案:
入棧:那個隊列不爲空,將八院所入隊到哪個隊列,如果都爲空,就隨機選擇一個。
出棧:把不爲空的隊列中除最後一個元素外的所有元素移動到另一個隊列中,然後出隊最後一個元素。

代碼實現:

package p_13_stack2queue;

import java.util.LinkedList;

public class Queue2Stack {
	private LinkedList queue1, queue2;
	int maxLen = 0;
	
	public Queue2Stack(int capacity){
		maxLen = capacity;
		queue1 = new LinkedList();
		queue2 = new LinkedList();
	}
	
	public boolean push(int item){
		if(size() >= maxLen){
			return false;
		}
		
		if(queue1.isEmpty()){
			queue2.add(item);
		}else {
			queue1.add(item);
		}
		return true;
	}
	public int pop(){
		if(size() == 0){
			throw new IndexOutOfBoundsException("the stack have null");
		}else {
			if(queue2.isEmpty()){
				while(queue1.size() > 1){
					queue2.add(queue1.poll());
				}
				return (int)queue1.poll();
			}else{
				while(queue2.size() > 1){
					queue1.add(queue2.poll());
				}
				return (int)queue2.poll();
			}
		}
		
	}
	
	public int size(){
		return queue1.size()+queue2.size();
	}
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章