zoukankan      html  css  js  c++  java
  • 两个栈实现队列的插入和删除(C++实现)

    代码:

    #include <iostream>
    #include <stack>
    using::std::stack;
    class Cqueue
    {
    public:
      stack<int>stack1,stack2;
      Cqueue(){};//构造函数;
      void appendTail(int val)
      {
        stack1.push(val);
      }
      int deleteHead()
      {
        if(stack1.empty())
        {
          return -1;
        }
        else
        {
          while(!stack1.empty())
          {
            int tem = stack1.top();
            stack1.pop();
            stack2.push(tem);
          }
          int deleteH = stack2.top();
          stack2.pop();
          while(!stack2.empty())
          {
            int temD = stack2.top();
            stack2.pop();
            stack1.push(temD);
          }
        std::cout << deleteH << ' ';
        return deleteH;
        }
      }
    };
    int main()
    {
      Cqueue q;
      for(int i=1;i<5;i++)
      {
        q.appendTail(i);
      }
      std::cout << "stack1中的元素:" << ' ';
      for(int i=1;i<5;i++)
      {
        int tem = q.stack1.top();
        q.stack1.pop();
        std::cout << tem << ' ';
      }
      std::cout << ' ';
      for(int i=1;i<5;i++)
      {
        q.appendTail(i);
      }
      q.deleteHead();
    }

     测试结果:

  • 相关阅读:
    利用LibreOffice进行WORD转PDF
    SpringBoot实践
    Solr学习笔记(一)
    HashMap原理(转)
    PDF.js展示本地文件
    设计模式之代理模式
    (一)DUBBO基本学习
    如何架构一个框架
    冒泡排序
    js 函数传数组参数
  • 原文地址:https://www.cnblogs.com/shiheyuanfang/p/13583037.html
Copyright © 2011-2022 走看看