C++标准库--stack 与其应用(栈元素的升序排列)

参考 网址:

https://blog.csdn.net/lanzhihui_10086/article/details/42426521(带有stack类的重新实现)

https://blog.csdn.net/m0_37561165/article/details/81114441(c++标准库stack和queue的简单使用)

1、stack的引入和使用

stack存在于STD<stack>中,可以通过#include<stack>引入

2、stack的定义

stack<T> s; 定义了一个T类型的stack对象,T可以是char,int,float等等

3、stack的使用

stack包含的主要功能函数为

push(e):元素e进栈

pop():删除栈顶元素,在标准库的实现中没有返回值,在这个网址上 https://blog.csdn.net/lanzhihui_10086/article/details/42426521,作者对栈进行了重写,使得pop时有返回值。

top():取得栈顶元素

empty():判断一个栈是否是非空

size():获取栈的大小

4、简单具体实例:

#include <iostream>
#include<stack>

using namespace std;

int main()
{

    stack<int> s;
    for(int i=0;i<10;i++)
        s.push(i);

    cout<<s.size()<<endl;

    while(!s.empty())
    {
        int e=s.top();
        s.pop();
        cout<<e<<" ";
    }
    cout<<endl;

    cout<<s.size()<<endl;


    return 0;
}

输出结果:

10
9 8 7 6 5 4 3 2 1 0
0

5、实现栈元素的升序排列,只能使用栈辅助,可以使用pop(),push(),empty(),top()函数

思路:定义一个辅助栈s1,每次从初始的栈s中pop出一个元素t与s1中元素进行比较,如果s1中的top()元素大于t,则将其pop出来压入初始栈s中,直到里面的元素大于等于t。最后得到了一个升序的排列,输出结果为降序的。

程序实现:

#include <iostream>
#include<stack>
using namespace std;
stack<int> asdSort(stack<int> s)
{
    stack<int> s1;
    while(!s.empty())
    {
        int t=s.top();
        s.pop();
        while(!s1.empty()&&t<s1.top())
        {
            s.push(s1.top());
            s1.pop();
        }
        s1.push(t);
    }
    return s1;
}

int main()
{
    stack<int> s;
    s.push(1);
    s.push(3);
    s.push(6);
    s.push(5);
    s.push(2);

    //cout<<s.size()<<endl;

    stack<int> s2;
    s2=asdSort(s);
    while(!s2.empty())
    {
        cout<<s2.top()<<endl;
        s2.pop();
    }

    return 0;
}

输出结果:

6
5
3
2
1

 

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值