用兩個棧實現隊列


題目描述

用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。
 1 import java.util.Stack;
 2 
 3 //用兩個棧來實現一個隊列,完成隊列的Push和Pop操作。 隊列中的元素為int類型。
 4 
 5 public class Main05 {
 6     public static void main(String[] args) {
 7         
 8     }
 9     
10     public class Solution {
11         Stack<Integer> stack1 = new Stack<Integer>();
12         Stack<Integer> stack2 = new Stack<Integer>();
13         
14         public void push(int node) {
15             stack1.push(node);
16         }
17         
18         public int pop() {
19             Integer re = null;
20             if(!stack2.isEmpty()) {
21                 re = stack2.pop();
22             }else {
23                 while(!stack1.isEmpty()) {
24                     re = stack1.pop();
25                     stack2.push(re);
26                 }
27                 if(!stack2.isEmpty()) {
28                     re = stack2.pop();
29                 }
30                 
31             }
32             return re;
33         }
34     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM