剑指offer五:两个栈实现一个队列
生活随笔
收集整理的這篇文章主要介紹了
剑指offer五:两个栈实现一个队列
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。
package com.jianzhioffer;import java.util.Stack;public class TwoStacks {Stack<Integer> stack1 = new Stack<Integer>();Stack<Integer> stack2 = new Stack<Integer>();public void push(int node) {stack1.push(node);}public int pop() {if(stack2.isEmpty()){while(!stack1.isEmpty()){stack2.push(stack1.pop());}}return stack2.pop();}public static void main(String[] args) throws Exception{TwoStacks s = new TwoStacks();s.push(1);s.push(2);int n = s.pop();System.out.println(n);s.push(3);n = s.pop();System.out.println(n);n = s.pop();System.out.println(n);s.push(4);n = s.pop();System.out.println(n);} }總結: 利用兩個棧實現一個隊列的功能,很有意思,這需要完全利用棧的先進后出的特點。 先把數據push到A棧中,然后將A棧元素pop到B棧,這樣B棧就將A棧的元素又反轉了下。
總結
以上是生活随笔為你收集整理的剑指offer五:两个栈实现一个队列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux下Tomcat重新启动以及日志
- 下一篇: 剑指offer六:旋转数组的最小数字