一 基本思路
將s1作為存儲空間,以s2作為臨時緩沖區。
入隊時,將元素壓入s1。
出隊時,將s1的元素逐個“倒入”(彈出並壓入)s2,將s2的頂元素彈出作為出隊元素,之后再將s2剩下的元素逐個“倒回”s1。
二 圖示
三 代碼實現(Java)
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.push(node); } public int pop() { while(!stack1.isEmpty()){ stack2.push(stack1.pop()); } int first=stack2.pop(); while(!stack2.isEmpty()){ stack1.push(stack2.pop()); } return first; } }
四 優化
入隊時,將元素壓入s1。
出隊時,判斷s2是否為空,如不為空,則直接彈出頂元素;如為空,則將s1的元素逐個“倒入”s2,把最后一個元素彈出並出隊。