LeetCode Implement Queue using Stacks (数据结构)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode Implement Queue using Stacks (数据结构)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
?
題意:
用棧來實現隊列。
?
思路:
一個棧是不夠的,至少要兩個。
(1)插入。永遠只插入到stack1中(插到棧頂)。
(2)彈出。如果stack2不為空,直接彈出stack2的棧頂,否則,將stack1中的所有元素轉移到stack2中,棧頂自然就是隊頭了,再彈出。
(3)返回隊頭。與(2)一樣。
(4)是否為空。判斷兩個棧是否同時為空即可。
?
只要保證stack2為空時才可以將stack1轉移到stack2中,就可以保證兩邊并不會產生混亂而出錯。
?
1 class Queue { 2 /* 3 // Push element x to the back of queue. 4 void push(int x) { 5 6 } 7 8 // Removes the element from in front of queue. 9 void pop(void) { 10 11 } 12 13 // Get the front element. 14 int peek(void) { 15 16 } 17 18 // Return whether the queue is empty. 19 bool empty(void) { 20 21 } 22 */ 23 stack<int> stack1,stack2; 24 public: 25 bool change()//當stack2為空時,將stack1轉到stack2中 26 { 27 while(!stack1.empty()) 28 { 29 stack2.push(stack1.top()); 30 stack1.pop(); 31 } 32 if(stack2.empty()) return true; 33 else return false; 34 } 35 void push(int x) 36 { 37 stack1.push(x); 38 } 39 void pop(void) 40 { 41 if(!stack2.empty()) stack2.pop(); 42 else if(!change()) stack2.pop(); 43 } 44 int peek(void) 45 { 46 if(!stack2.empty()) return stack2.top(); 47 else 48 { 49 if(!change()) return stack2.top(); 50 return 0; 51 } 52 } 53 bool empty(void) 54 { 55 if(stack1.empty()&&stack2.empty()) return true; 56 else return false; 57 } 58 }; AC代碼?
轉載于:https://www.cnblogs.com/xcw0754/p/4927606.html
總結
以上是生活随笔為你收集整理的LeetCode Implement Queue using Stacks (数据结构)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DB2 SQL 递归实现多行合并
- 下一篇: OpenGL中shader使用