两个栈模拟一个队列的行为

转载请注明出处

初始时,保证两个栈至少有一个为空;本程序的类中两个栈在初始化时默认为空栈;

队列特性为先进先出,

元素依次入栈s1内后,再将非空栈s1内的元素依次出栈全部压入到空栈s2内,就实现了原s1内后进来的数据放到了s2最下面,

这样栈s2的元素在逐个进行出栈操作时,就实现了模拟队列的的出队操作,出队顺序和s1进栈顺序相同,实现了先进先出,满足了队列性质;

  1 //两个栈模拟一个队列行为
  2 
  3 class SimQueue
  4 {
  5 public:
  6     SimQueue() { count = 0;}
  7     void SimPush(int);//入队:队尾增加元素,
  8     void SimPop(); //出队:删除队首元素
  9     int SimFront();//取队首元素
 10     int SimBack(); //取队尾元素
 11     bool SimEmpty();
 12     int SimSize();
 13 private:
 14     int count; //统计元素数量
 15     stack<int> s1;
 16     stack<int> s2;
 17 };
 18 
 19 inline 
 20 void SimQueue::SimPush(int num)
 21 {
 22     //初始时,将元素压到s1中;
 23     //如果初始时s1不为空,也无妨,但s2一定要为空
 24     //本程序的类中两个栈在初始化时默认为空栈;
 25     s1.push(num);
 26     ++count;
 27 }
 28 
 29 inline
 30     void SimQueue::SimPop()
 31 {
 32     if (s2.empty())
 33     {
 34         while (!s1.empty())
 35         {
 36             s2.push(s1.top());
 37             s1.pop();
 38         }
 39         s2.pop();
 40     }
 41     else
 42         s2.pop(); //多次删除队首元素值进入这个分支;
 43     --count;
 44 }
 45 inline
 46 int SimQueue::SimFront()
 47 {
 48     if (s1.empty()!=true&&s2.empty()==true)
 49     {
 50         while (!s1.empty())
 51         {
 52             s2.push(s1.top());
 53             s1.pop();
 54         }
 55         int tmp = s2.top();
 56         return tmp;
 57     }
 58     else
 59         return s2.top(); //s2不空时取队首元素值
 60     
 61 }
 62 inline
 63 int SimQueue::SimBack()
 64 {
 65     if (s1.empty()==true&&s2.empty()!=true)
 66     {
 67         while (s2.empty()!=true)
 68         {
 69             s1.push(s2.top());
 70             s2.pop();
 71         }
 72         return s1.top();
 73     }else
 74         return s1.top(); //以防s1不空时候取队尾元素值;
 75 }
 76 inline
 77 int SimQueue::SimSize()
 78 {
 79     return count;
 80 }
 81 inline
 82 bool SimQueue::SimEmpty()
 83 {
 84     return (count == 0);
 85 }
 86 
 87 
 88 int main()
 89 {
 90     SimQueue q;
    //入队
91 q.SimPush(1); 92 q.SimPush(2); 93 q.SimPush(3); 94 q.SimPush(4); 95 q.SimPush(5); 96 97 int qsize = q.SimSize(); 98 cout <<"queue size: " << qsize << endl; 99 cout << "多次取队首元素值: "; 100 cout << q.SimFront() <<" "; 101 cout << q.SimFront() <<endl; 102 cout << "多次取队尾元素值: "; 103 cout << q.SimBack()<<" "; 104 cout << q.SimBack()<<endl; 105 106 //队,栈均不提供遍历操作 107 cout << "删除元素1后: "; 108 q.SimPop(); //删除1, 109 cout << "current size: "<< q.SimSize()<<endl; 110 cout << "剩余元素出队: "<<endl; 111 cout << q.SimFront()<<","; 112 q.SimPop(); 113 cout << q.SimFront()<<","; 114 q.SimPop(); 115 cout << q.SimFront() <<","; 116 q.SimPop(); 117 cout << q.SimFront()<<endl; 118 q.SimPop(); 119 }

输出结果:

猜你喜欢

转载自www.cnblogs.com/strivingforever/p/9060116.html