用兩個棧來實現一個隊列,完成隊列的Push和Pop操做。

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

 1 using System.Collections.Generic;
 2 namespace JianZhiOffer
 3 {
 4     class StackToQueue
 5     {
 6         Stack<int> stk1 = new Stack<int>();
 7         Stack<int> stk2 = new Stack<int>();
 8 
 9         // 入隊
10         public void push(int node)
11         {
12             while (stk2.Count > 0)
13             {
14                 stk1.Push(stk2.Pop());
15             }
16 
17             stk1.Push(node);
18         }
19 
20         // 出隊
21         public int pop()
22         {
23             while (stk1.Count > 0)
24             {
25                 stk2.Push(stk1.Pop());
26             }
27 
28             return stk2.Pop();
29         }
30     }
31 }
相關文章
相關標籤/搜索