zoukankan      html  css  js  c++  java
  • 用一个栈实现另一个栈的排序(C++实现)

    要求:

    一个栈中的类型为整型,现在想将该栈从顶到底按从大到小的循序排序,只许申请一个栈。除此之外,可以申请新的变量,但不能申请额外的数据结构。

    代码:

    #include <iostream>
    #include <stack>
    using namespace std;
    void sortStack(stack<int> &sta)
    {
        stack<int> sta_1;
        while(!sta.empty()){
        int tem = sta.top();
        sta.pop();
        while(!sta_1.empty()&&sta_1.top()<tem){
          sta.push(sta_1.top());
          sta_1.pop();
        }
        sta_1.push(tem);
      }
        while(!sta_1.empty()){
          sta.push(sta_1.top());
          sta_1.pop();
        }
      }
    int main()
    {
        int a[] = {2,3,5,7,2};
        stack<int> sta;
        int i;
        for(i=0;i<5;i++)
        {
            sta.push(a[i]);
        }
        cout << "the stack before sorting are:" << endl;
        for(i=0;i<5;i++)
        {
            cout << sta.top() << endl;
            sta.pop();
        }
        for(i=0;i<5;i++)
        {
            sta.push(a[i]);
        }
        cout << "the stack after sorting are:" << endl;
        sortStack(sta);
        for(i=0;i<5;i++)
        {
            cout << sta.top() << endl;
            sta.pop();
        }
        return 0;
    }
     
    测试结果:
     
  • 相关阅读:
    python--io多路复用之select实现
    python--基于socket网络编程
    python--面向对象编程之学生选课系统练习
    python--异常处理
    python--面向对象之三个特性:封装、继承、多态
    python--反射机制
    python--生成器和迭代器
    elasticsearch 创建索引
    elasticsearch 集群搭建
    linux 安装Mosquitto
  • 原文地址:https://www.cnblogs.com/shiheyuanfang/p/13417065.html
Copyright © 2011-2022 走看看