1. 程式人生 > >佇列實現棧 和 棧實現佇列

佇列實現棧 和 棧實現佇列

如何僅用佇列實現一個棧?如何僅用棧實現一個佇列?

這是一個簡單的問題,但要是思維被限制了,就很難搞得定。大體的思路就是利用佇列先進先出的特點來實現一個棧,將佇列1的元素倒入佇列2中,將最後一個元素返回就是了。實現佇列也是同樣的道理。

/**
 * 利用兩個佇列實現一個棧
 * 功能:push,pop,peek
 */

import java.util.LinkedList;
import java.util.Queue;
public class C04_QueueToStack {
	public static class MyStack{
		private Queue<Integer>queue1;
		private Queue<Integer>queue2;
		public MyStack(){
			//Queue是一個介面,new 它的實現類
			queue1 = new LinkedList<Integer>();
			queue2 = new LinkedList<Integer>();
		}
		//壓棧
		public void push(int num){
			queue1.add(num);
		}
		//彈棧
		public int pop(){
			if(queue1.isEmpty()){
				throw new RuntimeException("the stack is empty!");
			}
			//佇列1的數全部壓進佇列2
			while(queue1.size()!=1){
				queue2.add(queue1.poll());
			}
			int res= queue1.poll();//res 記錄最後一個元素
			swap();
			return res;
		}
		//檢視棧
		public int peek(){
			if(queue1.isEmpty()){
				throw new RuntimeException("the stack is empty!");
			}
			//佇列1的數全部壓進佇列2
			while(queue1.size()!=1){
				queue2.add(queue1.poll());
			}
			int res = queue1.poll();
			queue2.add(res);
			swap();
			return res;
		}
		public boolean isEmpty(){
			return queue1.isEmpty();
		}
		//交換一下指標
		private void swap(){
			Queue<Integer>queue = queue1;
			queue1 = queue2;
			queue2 = queue;
		}
	}
	public static void main(String[] args) {
		MyStack myStack = new MyStack();
		myStack.push(3);
		myStack.push(6);
		myStack.push(9);
		System.out.println(myStack.peek()+"====");
		while(!myStack.isEmpty()){
			System.out.println(myStack.pop());
		}
	}
}

/**
 * 利用兩個棧實現一個佇列
 * 棧先進後出,佇列先進先出
 * 實現:push,pull,peek
 */
import java.util.Stack;
public class C03_StackToQueue {
	public static class MyQueue{
		private Stack<Integer>stack1;
		private Stack<Integer>stack2;
		public MyQueue(){
			stack1 = new Stack<Integer>();
			stack2 = new Stack<Integer>();
		}
		// 進佇列就壓在stack1
		public void push(int num){
			stack1.push(num);
		}
		//出佇列
		public int pull(){
			if(stack1.isEmpty()){
				throw new RuntimeException("the queue is empty!");
			}
			//stack1全部壓進stack2
			while(!stack1.isEmpty()){
				stack2.push(stack1.pop());
			}
			int res = stack2.pop();
			while(!stack2.isEmpty()){
				stack1.push(stack2.pop());
			}
			return res;
		}
		//查詢佇列
		public int peek(){
			if(stack1.isEmpty()){
				throw new RuntimeException("the queue is empty!");
			}
			while(!stack1.isEmpty()){
				stack2.push(stack1.pop());
			}
			int res = stack2.peek();
			while(!stack2.isEmpty()){
				stack1.push(stack2.pop());
			}
			return res;
		}
		public boolean isEmpty(){
			return stack1.isEmpty();
		}
	}
	public static void main(String[] args) {
		MyQueue myQueue = new MyQueue();
		myQueue.push(2);
		myQueue.push(4);
		myQueue.push(7);
		System.out.println(myQueue.peek()+"====");
		while(!myQueue.isEmpty()){
			System.out.println(myQueue.pull());
		}
	}
}