#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 << " ";
}
}
数据结构栈排序
最新推荐文章于 2025-04-24 11:29:36 发布

701

被折叠的 条评论
为什么被折叠?



