//运行环境:Clion //实验数据:34 5 67 23 19 90 -1 输出结果:5 19 23 34 67 90 //算法思路:先创建两个栈s1,s2,第一个存放数据,第二个辅助进行排序,通过比较栈顶元素的大小 //进行出栈入栈操作,最终把排好序的元素都压如s2中,然后把s2中部的数据都压入s1中,输出s1 #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define MAXSIZE 50 typedef struct { int data[MAXSIZE]; int top; }Stack;//顺序栈结构 void InitStack(Stack * S);//初始化栈 bool StackEmpty(Stack * S);//判断栈是否为空 bool Push(Stack * S, int c);//压栈函数 bool Pop(Stack * S, int * c);//出栈函数 void Sort(Stack * S1, Stack * S2);//排序函数,参数为两个栈,分别为目标栈和辅助栈 int main(void) { Stack * S1 = (Stack *)malloc(sizeof(Stack)); Stack * S2 = (Stack *)malloc(sizeof(Stack)); int x, y; InitStack(S1); InitStack(S2); scanf("%d", &x); while (x != -1)//输入为-1时,停止输入 { Push(S1, x); scanf("%d", &x); } Sort(S1, S2);//排序 while (!StackEmpty(S1))//输出目标栈中的元素
用栈进行插入排序的算法
最新推荐文章于 2022-08-02 23:01:19 发布