牛客网. 用一个栈实现另一个栈的排序

该博客探讨了如何使用两个栈实现一个排序的功能。首先介绍了两种思路:一种是不断对比栈顶元素与下一个元素并调整,另一种是通过辅助栈进行元素的比较与转移。博主指出,虽然两种方法的时间复杂度都是O(n^2),但更倾向于第二种方法,因为它更直观地满足题目需求。随后,提供了C++代码示例来展示这两种方法的实现过程。

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

题目概述

解题思路

两种思路:其一是每次比较一下当前栈中top元素和下一个元素的大小,然后把小的/大的放到另一个栈中;这样清空一遍以后,相当于把一个数组的相邻元素大小都比较了一遍;然后我们反过来再进行类似的操作,把大的/小的放到另一个栈中,如此反复,直至某次操作以后,不再需要我们颠倒top和下一个元素的顺序,表明排序结束。

另一种做法是:将排序的栈记为A,辅助的栈记为B,在A上pop元素,记得到的元素为a。如果a不大于B的栈顶元素/B为空,则将a放入B;如果a大于B的栈顶元素,则将B中元素依次放入A,直到a不大于B中栈顶元素,再将a放入B。

这两种算法的时间复杂度应该都是O(n^2)。不过我更喜欢第二种思路,它更符合题目的要求。

方法性能

样例代码

#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<cstring>
#include<queue>
#include<iomanip>

using namespace std;

int main()
{
	int list_num, val_num, temp, temp_top;
	bool signal = false;
	stack <int> ori_list, sort_list;
	cin >> list_num;
	for (int vi = 0; vi < list_num; ++vi)
	{
		cin >> val_num;
		ori_list.push(val_num);
	}
	do
	{
		if (signal == false)
			signal = true;
		else
			break;
		temp = ori_list.top();
		ori_list.pop();
		while (!ori_list.empty())
		{
			temp_top = ori_list.top();
			ori_list.pop();
			if (temp_top > temp)
			{
				sort_list.push(temp_top);
				signal &= false;
			}
			else
			{
				sort_list.push(temp);
				temp = temp_top;
			}
		}
		sort_list.push(temp);

		if (signal == false)
			signal = true;
		else
			break;
		temp = sort_list.top();
		sort_list.pop();
		while (!sort_list.empty())
		{
			temp_top = sort_list.top();
			sort_list.pop();
			if (temp_top < temp)
			{
				ori_list.push(temp_top);
				signal &= false;
			}
			else
			{
				ori_list.push(temp);
				temp = temp_top;
			}
		}
		ori_list.push(temp);

	} while (signal == false);

	while (!ori_list.empty())
	{
		temp = ori_list.top();
		ori_list.pop();
		sort_list.push(temp);
	}
	while (!sort_list.empty())
	{
		temp = sort_list.top();
		sort_list.pop();
		ori_list.push(temp);
	}

	while (!ori_list.empty())
	{
		temp = ori_list.top();
		cout << temp << ' ';
		ori_list.pop();
	}
	while (!sort_list.empty())
	{
		temp = sort_list.top();
		cout << temp << ' ';
		sort_list.pop();
	}

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值