1. 程式人生 > >劍指offer五之用兩個棧實現隊列

劍指offer五之用兩個棧實現隊列

stat play color return ret gif 隊列 tac min

一、題目

  用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。

二、思路

1、Push操作:將數據直接壓入stack1即可

2、Pop操作:將stack1中的數據全部彈出壓入到stack2中,然後將stack1中的數據全部彈出即可

註意:要將stack1中的數據全部壓入到stack2中後,才能將stack2中的數據彈出

三、代碼

1、解決方法

技術分享
import java.util.Stack;

public class Solution {

    Stack<Integer> stack1 = new Stack<Integer>();//
棧1 Stack<Integer> stack2 = new Stack<Integer>();//棧2 public void push(int node) { //push操作 stack1.push(node); } public int pop() { //pop操作 if (stack1.empty() && stack2.empty()) { throw new RuntimeException("Queue is empty!"); }
if (stack2.empty()) { while (!stack1.empty()) { stack2.push(stack1.pop()); } } return stack2.pop(); } }
View Code

2、測試方法

技術分享
public class TestMain {
    public static void main(String[] args) {
        int[] a={1,2,3,4,5};

        Solution solution
=new Solution(); for(int i=0;i<a.length;i++){ solution.push(a[i]); //push的順序1 2 3 4 5 } for(int j=0;j<a.length;j++){ int val= solution.pop(); System.out.print(val+" "); //pop的順序 1 2 3 4 5 } } }
View Code

---------------------------------------------------------------------------------------------------------------------------------------------

參考鏈接:https://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6

劍指offer五之用兩個棧實現隊列