[关闭]
@kakadee 2016-06-04T07:06:28.000000Z 字数 1152 阅读 1286

栈和队列

编程 算法


1. 用两个栈实现队列

描述:

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

代码:

  1. class Solution
  2. {
  3. public:
  4. void push(int node) {
  5. stack1.push(node);
  6. }
  7. int pop() {
  8. int tmp = 0;
  9. while(!stack1.empty()){
  10. stack2.push(stack1.top());
  11. stack1.pop();
  12. }
  13. if(stack2.empty()){
  14. cout<<"empty!"<<endl;
  15. return 0;
  16. }
  17. else {
  18. tmp = stack2.top();
  19. stack2.pop();
  20. }
  21. while(!stack2.empty()){
  22. stack1.push(stack2.top());
  23. stack2.pop();
  24. }
  25. return tmp;
  26. }
  27. private:
  28. stack<int> stack1;
  29. stack<int> stack2;
  30. };

2. 栈的压入、弹出序列

描述:

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。

代码:

  1. class Solution {
  2. public:
  3. bool IsPopOrder(vector<int> pushV,vector<int> popV) {
  4. if(pushV.size() == 0)
  5. return false;
  6. int index1 = 0,index2 = 0;
  7. // 模拟栈的操作
  8. stack<int> s;
  9. while(index1 < pushV.size()) {
  10. s.push(pushV[index1++]);
  11. while (index2 < popV.size() && popV[index2] == s.top()){
  12. s.pop();
  13. index2++;
  14. }
  15. }
  16. return s.empty();
  17. }
  18. };

3. 包含min函数的栈

描述:

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

代码:

  1. class Solution {
  2. public:
  3.         void push(int value) {
  4.                 s.push(value);
  5.                 if(value <= minNum.top() || minNum.empty())
  6.                         minNum.push(value);
  7.         }
  8.         void pop() {
  9.                 if(s.top() == minNum.top()){
  10.                         minNum.pop();
  11.                 }
  12.                 s.pop();
  13.         }
  14.         int top() {
  15.                 return s.top();
  16.         }
  17.         int min() {
  18.                 return minNum.top();
  19.         }
  20. private:
  21.         stack<int> minNum;
  22.         stack<int> s;
  23. };
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注