[演算法題打卡-1] 劍指 Offer 09. 用兩個棧實現佇列
阿新 • • 發佈:2021-06-26
地址:https://leetcode-cn.com/problems/yong-liang-ge-zhan-shi-xian-dui-lie-lcof/
分析:
要求用兩個棧實現一個佇列。棧的特點是,先進後出。佇列的特點是,先進先出
元素先放進棧1,再取出元素放進棧2,在這個過程中,元素的順序就被顛倒過來了。
只要保證一個棧只存元素,另一個元素只取元素(如果取不到元素,就去另一個棧pop),就能實現佇列的功能。
程式碼:
class CQueue { LinkedList<Integer> stack1; LinkedList<Integer> stack2;public CQueue() { stack1 = new LinkedList<>(); stack2 = new LinkedList<>(); } public void appendTail(int value) { stack1.push(value); } public int deleteHead() { if(!stack2.isEmpty()) { return stack2.pop(); }if(stack1.isEmpty()) { return -1; }else { while(!stack1.isEmpty()) { stack2.push(stack1.pop()); } return stack2.pop(); } } } /** * Your CQueue object will be instantiated and called as such: * CQueue obj = new CQueue(); * obj.appendTail(value); * int param_2 = obj.deleteHead();*/