第四次上机作业SortUsingStackOnly

1. SortUsingStackOnly.cpp
Write a function StackSort to sort a stack in ascending order.
The following are the only functions that should be
used to write this function: push | pop | top | empty.
void  StackSort(stack<int>& s);

PostCondition: sorted stack with minimum on the top

作业要求大致是用一个栈实现升序排列,具体过程用一个变量存储栈顶元素,然后两个栈互相倒元素,直至找到满足条件的位置插入即可。

srand():srand和rand()配合使用产生伪随机数序列。rand函数在产生随机数前,需要系统提供的生成伪随机数序列的种子,rand根据这个种子的值产生一系列随机数。如果系统提供的种子没有变化,每次调用rand函数生成的伪随机数序列都是一样的。

#include <bits/stdc++.h>
#include <cstdlib>
#include <ctime>
using namespace std;
void StackSort(stack<int>& s)
{
    stack<int> Q;
    int t;
    t=s.top();
    s.pop();
    Q.push(t);
    while(!s.empty())
    {
        t=s.top();//取出栈顶元素
        s.pop();
        int cnt=0;
        while(t<Q.top())//如果不能放入则将栈中元素弹出
        {
            s.push(Q.top());
            Q.pop();
            cnt++;//记录弹出个数
            if(Q.empty())break;
        }
        Q.push(t);
        while(cnt--)
        {
            Q.push(s.top());
            s.pop();//依次放回
        }
    }
    int len=Q.size();
    while(len--)
    {
        s.push(Q.top());
        Q.pop();
    }
}

void display(stack<int> s)
{
    while (!s.empty()) cout<<s.top()<<endl,s.pop();
    cout<<endl;
}
int main(int argc,char**argv)
{
    const int n{20};
    srand((unsigned)time(0));//用time作为rand()函数的种子
    stack<int> s;
    for (int i{0}; i<n; i++) s.push(rand()%100);//获得100内随机数
    cout<<"Before sorting:"<<endl<<endl;
    display(s);
    cout<<"After sorting:"<<endl;
    StackSort(s);
    display(s);
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值