实现入栈元素排序
头文件stack.h
#ifndef _STACK_H_
#define _STACK_H_
#include <stdlib.h>
#define SUCCESS 10000
#define FAILURE 10001
#define TRUE 10002
#define FALSE 10003
#define SIZE 10 //栈的容量
typedef int ElemType;
struct Stack
{
int top; //栈顶元素的位置(栈顶指针)
ElemType *data;
};
typedef struct Stack stack;
int StackInit(stack **s); // 栈的初始化
int StackEmpty(stack *s); // 判断栈是否为空
int push(stack *s, ElemType e); // 入栈
int GetTop(stack *s); // 得到栈顶元素
int pop(stack *s); // 出栈
#endif
子函数文件 stack.c
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"
int stackInit(stack **s) //初始化
{
(*s) = (stack *)malloc(sizeof(stack)*1);
if(NULL == (*s)) //入参判断
{
return FAILURE;
}
(*s)->top = -1;
(*s)->data = (ET *)malloc(sizeof(ET)*10); //分配空间(堆空间)
if(NULL == (*s)->data)
{
return FAILURE;
}
return SUCCESS;
}
int stackEmpty(stack *s)
{
return (s->top == -1)? TURE:FALSE; //空栈时 top = -1;栈有一个元素时,top = 0.
}
int push(stack *s,ET e)
{
if(s->top == 9 || NULL == s) //top == 9时,栈满了,不能再入栈
{
return FAILURE;
}
s->data[s->top + 1] = e;
s->top++; //存一个数据,top + 1
return SUCCESS;
}
int Gettop(stack *s)
{
if(s->top == -1 || NULL == s)
{
return FAILURE;
}
else
{
return s->data[s->top]; //返回栈顶元素
}
}
int pop(stack *s)
{
if(s->top == -1 || NULL == s) //top = -1时不能再出栈,因为栈此时为空
{
return FAILURE;
}
else
{
return SUCCESS;
}
}
测试文件test.c
#include "stack.h"
int main()
{
int i, num, tmp;
stack *s1, *s2;
if (stackInit(&s1) != SUCCESS || stackInit(&s2) != SUCCESS)
{
printf("Init Failure!\n"); //判断初始化的两个栈是否成功
}
for (i = 0; i < SIZE; i++)
{
scanf("%d", &num);
if (i == 0)
{
push(s1, num); //ru栈
}
else
{
if (num >= GetTop(s1))
{//比较后一个入栈的元素与前一个入栈的元素比较,如果后面入栈的元素比前一个入栈的元素大,直接入栈
push(s1, num);
}
else
{//否则把前面的元素值大的放到另一个栈中,把小的先放进去,再把大放进来
while (StackEmpty(s1) != TRUE && num < GetTop(s1))
{
tmp = GetTop(s1);
pop(s1);
push(s2, tmp);
}
push(s1, num);
while (StackEmpty(s2) != TRUE) //把s1栈放入s2栈的元素再放回s1中
{
tmp = GetTop(s2);
pop(s2);
push(s1, tmp);
}
}
}
}
for (i = 0; i < SIZE; i++)
{
printf("%d ", GetTop(s1)); //s1所有元素出栈
pop(s1);
}
return 0;
}