CareerCup 3.6

本文介绍了一种使用额外栈对堆栈进行升序排序的方法,包括两种实现方式:一种是非递归方法,时间复杂度为O(n^2),另一种是递归方法,同样具有O(n^2)的时间复杂度。方法通过循环从原始堆栈中移除元素,并将这些元素重新插入到新的堆栈中,确保每次插入操作后新堆栈保持升序排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

3.6 Write a program to sort a stack in ascending order (with biggest items on top). You may use additional stacks to hold items, but you may not copy the elements into any other data structure (such as an array). The stack supports the following operations:push, pop, peek and isEmpty.

Approach 1: use another stack - O(n^2)

stack<int> sort(stack<int> &s) {
    stack<int> r;
    while (!s.empty()) {
        int x = s.top();
        s.pop();
        while (!r.empty() && r.top() > x) {
            s.push(r.top());
            r.pop();
        }
        r.push(x);
    }
    return r;
}
Approach 2: Recursive - O(n^2)

void insert(stack<int> &s, int x) {
    if (s.empty()) {
        s.push(x);
    } else if (s.top() < x) {
        s.push(x);
    } else {
        int y = s.top();
        s.pop();
        insert(s, x);
        s.push(y);
    }
}

void sort(stack<int> &s) {
    if (!s.empty()) {
        int x = s.top();
        s.pop();
        sort(s);
        insert(s, x);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值