题目:设有一个元素类型为整型的栈S,设计一个算法,借助另一个栈实现把该栈的所有元素从栈顶到栈底按从小到大次序排列起来
思想:
将大于栈顶元素就出栈,然后存入原来的栈中,直到栈顶元素不小于当前要插入的元素。
代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MaxSize 100
/*
* 题目:设有一个元素类型为整型的栈S,设计一个算法,借助另一个栈实现把该栈的所有元素从栈顶到栈底按从小到大次序排列起来
* */
typedef struct
{
int data[MaxSize];
int top;
}Sqstack;
void InitStack(Sqstack &S)
{
S.top = -1;
}
int StackEmpty(Sqstack S)
{
if(S.top == -1)
{
printf("栈空!");
return 1;
}
else
{
printf("栈不空!");
return 0;
}
}
void Push(Sqstack &S,int &x)
{
if(S.top==MaxSize)
{
printf("栈满,无法进栈!");
}
S.top++;
S.data[S.top] = x;
}
void Pop(Sqstack &S,int &x)
{
if(S.top==-1)
{
printf("栈空,无法出栈!");
}
x = S.data[S.top--];
}
int GetTop(Sqstack S,int &x)
{
if(S.top==-1)
{
printf("栈空,无法获取栈顶元素!");
return 0;
}
x = S.data[S.top];
return 1;
}
void Print(Sqstack S)
{
while(S.top>=0)
{
printf("%d ",S.data[S.top--]);
}
printf("\n");
}
void Dispose()
{
Sqstack S;
InitStack(S);
int n;
printf("请输入要输入栈中的元素个数:");
scanf("%d",&n);
int data;
printf("请输入要输入栈中的元素:");
for(int i=0;i<n; i++)
{
scanf("%d",&data);
Push(S,data);
}
printf("目前栈中元素为:");
Print(S);
Sqstack Q;
InitStack(Q);
int x;
while(StackEmpty(S)!=1)
{
Pop(S,x);
int e;
GetTop(Q,e);
if(StackEmpty(Q)==1 || x<e)
{
Push(Q,x);
}
else
{
int count = 0;
while(Q.data[Q.top]<x)
{
int k;
Pop(Q,k);
Push(S,k);
count++;
}
Push(Q,x);
while(count>0)
{
count--;
Pop(S,x);
Push(Q,x);
}
}
}
Print(Q);
}
int main() {
Dispose();
return 0;
}