栈的排序(c++)

该博客介绍了如何使用C++编程实现栈内的排序,通过借鉴冒泡排序的思路,利用递归在不借助额外数据结构的情况下完成栈元素的排序。提供了一种巧妙的空间复杂度为O(1)的解决方案。
摘要由CSDN通过智能技术生成

题目要求如下:

试设计算法,将栈S中的元素排序。要求不用辅助数据结构,仅通过对S自身的操作完成S中元素的排序。

实现思路如下:

借鉴冒泡排序的思路利用递归实现栈的排序,空间复杂度为O(1)

代码如下:

#include"pch.h"
#include<iostream>
#include<stack>
#include<cstdlib>
#include<ctime>
using namespace std;

const int LENGTH = 10;
stack<int> initialStack()
{
	stack<int> result;
	for (int i = 0; i < 10; i++)
	{
		result.push(rand() % 10);
	}
	return result;
}
void printStack(stack<int> st)
{
	for (int i = 0; i < 10; i++)
	{
		cout << st.top();
		st.pop();
		if (i != 9)
			cout << " ";
		else
			cout << endl;
	}
}
void helpReorderStack(stack<int>& st, int tag)
{
	if (st.size() == 0)
	{
		st.push(tag);
		return;
	}
	int num = st.top();
	st.pop();
	if (num > tag)
	{
		int temp = num;
		num = tag;
		tag = temp;
	}
	helpReorderStack(st, tag
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
链式的冒泡排序可以通过遍历链表来实现。具体步骤如下: 1. 遍历链表,比较相邻的两个节点的值,如果前一个节点的值大于后一个节点的值,则交换它们的值。 2. 继续遍历链表,直到没有节点需要交换。 下面是具体的实现代码: ```c++ #include <iostream> using namespace std; struct Node { int data; Node* next; }; class LinkedStack { public: LinkedStack() { top = NULL; } ~LinkedStack() { Node* p; while (top != NULL) { p = top; top = top->next; delete p; } } void push(int val) { Node* p = new Node; p->data = val; p->next = top; top = p; } int pop() { if (top == NULL) { cout << "Stack is empty!" << endl; return -1; } Node* p = top; int val = p->data; top = top->next; delete p; return val; } void bubbleSort() { if (top == NULL || top->next == NULL) { return; } Node* p = top; while (p != NULL) { Node* q = top; while (q->next != NULL) { if (q->data > q->next->data) { int temp = q->data; q->data = q->next->data; q->next->data = temp; } q = q->next; } p = p->next; } } void print() { Node* p = top; while (p != NULL) { cout << p->data << " "; p = p->next; } cout << endl; } private: Node* top; }; int main() { LinkedStack stack; stack.push(3); stack.push(1); stack.push(4); stack.push(2); cout << "Before sorting: "; stack.print(); stack.bubbleSort(); cout << "After sorting: "; stack.print(); return 0; } ``` 运行结果为: ``` Before sorting: 2 4 1 3 After sorting: 1 2 3 4 ``` 注意,链式的冒泡排序需要遍历整个链表,时间复杂度为 O(n^2),因此不适用于对大型数据进行排序
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值