package com.open.learncode.算法.java.leetcode.A1_棧與隊(duì)列;
import com.open.learncode.算法.base.PrintUtils;
import java.util.Stack;
/**
題目:
用兩個(gè)棧來(lái)實(shí)現(xiàn)一個(gè)隊(duì)列埂陆,完成n次在隊(duì)列尾部插入整數(shù)(push)和在隊(duì)列頭部刪除整數(shù)(pop)的功能樱衷。
隊(duì)列中的元素為int類型庵楷。保證操作合法,即保證pop操作時(shí)隊(duì)列內(nèi)已有元素蹂随。
<p>
數(shù)據(jù)范圍:
n <= 1000
<p>
復(fù)雜度分析:
-
時(shí)間復(fù)雜度O(1),空間復(fù)雜度O(n)
*/
public class JZ09_1_用兩個(gè)棧實(shí)現(xiàn)隊(duì)列 {public static void main(String[] args) {
// 測(cè)試示例
Solution solution = new Solution();
solution.push(1);
solution.push(2);
PrintUtils.getInstance().print(solution.pop());
PrintUtils.getInstance().print(solution.pop());
}private static class Solution {
private Stack<Integer> inStack = null;
private Stack<Integer> outStack = null;public Solution() { inStack = new Stack<Integer>(); outStack = new Stack<Integer>(); } public void push(int node) { inStack.push(node); } public int pop() { if (outStack.isEmpty()) { while (!inStack.isEmpty()) { outStack.push(inStack.pop()); } } return outStack.isEmpty() ? -1 : outStack.pop(); }
}
}