面試中常出現讓你手寫兩個隊列實現一個棧,兩個棧實現一個隊列的問題,很是頭疼!今天就仔細將我分析,思考過的Java代碼給大家分享一下:(一)兩個隊列實現一個棧:
兩個隊列添加元素,哪個隊列為空,由於在輸出元素時,要進行相應元素的移動(除去尾部元素),所以要在對應不為空的隊列進行元素的添加;在輸出數據時,要進行兩個隊列的變相操作,不為空的隊列要依次向為空的隊列中添加元素,直到尾元素輸出即可!
/** * 兩個隊列實現一個棧 * @auther yangchao * @date 2019/7/18 */ public class TwoQueueImplStack { private Queue<Integer> queue1 = new ArrayDeque<>(); private Queue<Integer> queue2 = new ArrayDeque<>(); /** * 向棧中壓入數據 * @param element */ public void push(Integer element) { //兩個隊列為空時,優先考慮queue1 if (queue1.isEmpty() && queue2.isEmpty()) { queue1.add(element); return; } //如果queue1為空,queue2有數據,直接放入queue2 if (queue1.isEmpty()) { queue2.add(element); return; } //如果queue1為空,queue2有數據,直接放入queue2 if (queue2.isEmpty()) { queue1.add(element); return; } } /** * 取出棧中的數據 * @return */ public Integer poll() { //兩個隊列為空時,直接拋出異常 if (queue1.isEmpty() && queue2.isEmpty()) { throw new RuntimeException("stack is empty"); } //如果queue1為空,將queue2中的元素依次加入到 queue1, 彈出最后一個元素 if (queue1.isEmpty()) { while(queue2.size() > 1) { queue1.add(queue2.poll()); } return queue2.poll(); } //如果queue2為空,將queue1中的元素依次加入到 queue2, 彈出最后一個元素 if (queue2.isEmpty()) { while(queue1.size() > 1) { queue2.add(queue1.poll()); } return queue1.poll(); } return null; } public static void main(String[] args) { TwoQueueImplStack qs = new TwoQueueImplStack(); qs.push(2); qs.push(4); qs.push(7); qs.push(5); System.out.println(qs.poll()); System.out.println(qs.poll()); qs.push(1); System.out.println(qs.poll()); } }
輸出結果:
(二)兩個棧實現一個隊列:
第一個棧只負責添加元素,第二個棧在彈出元素時,首先判斷當前棧是否為空,若為空就直接將其第一個棧中的數據全部壓入第二個棧中,然后輸出棧頂元素,即可實現隊列效果;若第二個棧中有數據,添加直接將其數據壓入第一個棧中,輸出時直接輸出第二個棧頂的元素即可!
/** * 兩個棧實現一個隊列 * @auther yangchao * @date 2019/7/18 */ public class TwoStackImplQueue { private Stack<Integer> stack1 = new Stack<>(); private Stack<Integer> stack2 = new Stack<>(); /** * stack1只負責壓入隊列元素 * @param element */ public void push(Integer element) { stack1.add(element); } /** * 取出隊列頂部元素 * @return */ public Integer poll() { //若stack2為空,將 stack1 中的元素壓入 stack2 if (stack2.isEmpty()) { while (stack1.size() > 0) { stack2.add(stack1.pop()); } } if (stack2.isEmpty()) { throw new RuntimeException("queue is Empty!"); } Integer head = stack2.pop(); return head; } public static void main(String[] args) { TwoStackImplQueue sq = new TwoStackImplQueue(); sq.push(1); sq.push(3); sq.push(5); sq.push(4); sq.push(2); System.out.println(sq.poll()); System.out.println(sq.poll()); sq.push(7); System.out.println(sq.poll()); } }
輸出結果:
每天進步一點點,繼續加油......