数据结构:利用栈T将栈S升序
#include "SeqStack.h"
//升序栈
SeqStack YouXuZhan(SeqStack *s)
{
SeqStack t;//临时栈
StackInitiate(&t);//初始化
int x;//s栈出栈值
int y;//t栈出栈值
while (StackNotEmpty(*s))
{
StackPop(s, &x);//s出栈
while (StackNotEmpty(t) && StackTop(t)>x)//如果t栈不为空 且 t栈栈顶值大于x
{
StackPush(s, StackTop(t));//将t栈栈顶值入s栈
StackPop(&t, &y);//t栈出栈
//一直循环到t栈为空或StackTop(t)<=x
}
StackPush(&t, x);//找到不大于StackTop(t)的x值后将x压入t;
}
return t;
}
int main()
{
SeqStack s;
int x;
StackInitiate(&s);
StackPush(&s, 1);
StackPush(&s, 4);
StackPush(&s, 3);
StackPush(&s, 2);
s=YouXuZhan(&s);
printf("排序后:\n");
while (StackNotEmpty(s))
{
StackPop(&s, &x);
printf("%d ", x);
}
return 0;
}
//运行结果:
排序后:
4 3 2 1
(出栈后与原栈序相反)
网络上志同道合,我们一起学习网络安全,一起进步,QQ群:694839022