1. 程式人生 > >佇列結構實現棧結構,棧結構實現佇列結構

佇列結構實現棧結構,棧結構實現佇列結構

用佇列實現棧結構,可以用兩個佇列來實現。一個用來插入資料,一個用來輔助實現pop和push。push時直接把數放在第一個佇列中,pop時,先把佇列1裡除了最後一個push進去的數全部push進佇列2中,最後的元素就是我們要pop出的元素,pop出後再把佇列2中的數再放進佇列1中。獲取棧頂元素和方法和pop的方法相同。

用棧實現佇列結構,同樣要用兩個棧來實現。一個棧用來poll資料,一個用來push資料。push時,都把數放進棧1中。poll時,把棧1的資料都放進棧2中,再poll。獲取棧頂元素的方式和poll的方法相同。

程式碼如下所示:

public class StackAndQueueConvert {
	public static void main(String[] args) {
		
	}
	public static class TwoStacksQueue {
		private Stack<Integer> stackPush;
		private Stack<Integer> stackPop;
		public void push(int pushInt) {
			stackPush.push(pushInt);
		}
		public int poll() {
			if(stackPop.empty() && stackPush.empty()) {
				throw new RuntimeException("Queue is empty!");
			} else if (stackPop.empty()) {
				while(!stackPop.empty()) {
					stackPop.push(stackPush.pop());
				}
			}
			return stackPop.pop();
		}
		public int peek() {
			if(stackPop.empty() && stackPush.empty()) {
				throw new RuntimeException("Queue is empty!");
			} else if(stackPop.isEmpty()) {
				while(!stackPop.empty()) {
					stackPop.push(stackPush.pop());
				}
			}
			return stackPop.peek();
		}
	}
	public static class TwoQueuesStack {
		private Queue<Integer> queue;
		private Queue<Integer> help;
		
		public TwoQueuesStack() {
			queue = new LinkedList<Integer>();
			help = new LinkedList<Integer>();
		}
		
		public void push(int pushInt) {
			queue.add(pushInt);
		}
		
		public int peek() {
			if(queue.isEmpty()) {
				throw new RuntimeException("Stack is empty!");
			}
			while(queue.size() != 1) {
				help.add(queue.poll());
			}
			int res = queue.poll();
			help.add(res);
			swap();
			return res;
		}
		
		public int pop() {
			if(queue.isEmpty()) {
				throw new RuntimeException("Stack is empty!");
			}
			while(queue.size() > 1) {
				help.add(queue.poll());
			}
			int res = queue.poll();
			swap();
			return res;
		}
		
		private void swap() {
			Queue<Integer> tmp = help;
			help = queue;
			queue = tmp;
		}
	}
}