棧是先入后出,隊列是先入先出。根據這個思想,可以用一個棧作為入隊,另一個棧作為出隊。只要把第一個棧的棧頂的元素壓入第二個棧就好了,出隊的時候輸出第二個棧的棧頂,如果第二個棧的空了就需要不斷操作從第一個棧的棧頂壓入第二個棧,但是如果第一個棧也空了,那就說明所有元素都輸出來了。
import java.util.Stack; /** * 用棧實現隊列 * @author rhq * */ public class StackQueue { // 作為入隊序列 private Stack<Integer> stack1 = new Stack<Integer>(); // 作為出隊序列 private Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { // 入隊時,要保證stack2為空 while (!stack2.empty()) { stack1.push(stack2.peek()); stack2.pop(); } stack1.push(node); System.out.println("入隊元素是:" + stack1.peek()); } public int pop() { // 出隊時,要保證stack1為空 while (!stack1.empty()) { stack2.push(stack1.peek()); stack1.pop(); } System.out.println("出隊元素是:" + stack2.peek()); int temp = stack2.peek(); stack2.pop(); return temp; } public static void main(String[] args) { StackQueue so = new StackQueue(); so.push(1); so.push(2); so.push(3); so.pop(); so.pop(); so.push(4); so.pop(); so.push(5); so.pop(); so.pop(); }
最終結果
入隊元素是:1 入隊元素是:2 入隊元素是:3 出隊元素是:1 出隊元素是:2 入隊元素是:4 出隊元素是:3 入隊元素是:5 出隊元素是:4 出隊元素是:5