数据结构栈排序

#include<iostream>
#define MaxSize 10
using namespace std;
#include<ctime>
typedef struct node
{
	int data[MaxSize];
	int top;
}SqStack;
class Stack
{
public:
	void Initialization(SqStack& s)
	{
		s.top = -1;
	}
	void Push(SqStack &st, int &value)
	{
		if (st.top == MaxSize - 1)
		{
			cout << "栈满" << endl;
			return;
		}
		++st.top;
		st.data[st.top] = value;
	}
	void Pop(SqStack &st,int &value)
	{
		if (st.top == -1)
		{
			cout << "栈空" << endl;
			return;
		}
		value = st.data[st.top];
		--st.top;
	}
	void StackSort(SqStack& st)//descending order(降序)
	{
		SqStack tempst;
		Initialization(tempst);
		//use two variables to record the top elements of two stacks
		//采用两个临时变量记录两个栈的栈顶元素
		int tempe;
		int e;
		while (st.top >= 0)
		{
			Pop(st, e);
			cout << "st:出栈元素 " << e << " ==>"<<endl;
			while (tempst.top >=0)
			{
				tempe = tempst.data[tempst.top];
				//the sequential stack should be sorted in descending order,and the temporary stack should be sorted in ascending order
				//顺序栈要想降序排序,临时栈就得升序排序
				if (tempe > e)//if the top element of the temporary stack is larger than the sequential stack ,it will pop up(当顺序栈的栈顶元素大于顺序栈,那就要弹栈)
				{
					Pop(tempst, tempe);
					cout << "tempst:栈顶元素" << tempe << "退栈,为保留数据进入到st中" << endl;
					Push(st, tempe);
				}
				else
				{
					cout << "tempst" << tempe << "<" << e << "退出循环" << endl;
					break;
				}
			}
			
			Push(tempst, e);
			
			cout << "st中的" << e << "进入tempst中" << endl<<endl;
		}
		while (tempst.top >= 0)
		{
			int e;
			Pop(tempst, e);
			Push(st, e);
		}
		
		cout << "排序完毕" << endl;
	}
};
int main()
{
	Stack stack;
	SqStack st;
	int a[4];
	//randomly generate 4 numbers(随机产生4个数)
	srand((unsigned)time(0));
	for (int i = 0; i < 4; ++i)
		a[i] = rand() % 20;//在0~19
	stack.Initialization(st);
	cout << "依次进栈元素:";
	for (int i = 0; i < 4; ++i)
	{
		cout << a[i]<<"  ";
		stack.Push(st, a[i]);
	}
	cout << endl;
	stack.StackSort(st);
	int e;
	while(st.top>=0)
	{
		stack.Pop(st, e);
		cout << e << "  ";
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值