头文件 SequenceStack.h
#ifndef SEQUENCESTACK_H
#define SEQUENCESTACK_H
#define SIZE 10
#define SUCCESS 10000
#define FAILURE 10001
#define TRUE 10002
#define FALSE 10003
struct SequenceStack
{
int *data;
int top;
};
typedef struct SequenceStack Stack;
int InitStack(Stack **s);
int push(Stack *s,int e);
int EmptyStack(Stack *s);
int GetTop(Stack *s);
int DestoryStack(Stack **s);
int ClearStack(Stack *s);
#endif
自定义文件 SequenceStack.c
#include "SequenceStack.h"
#include <stdlib.h>
int InitStack(Stack **s) //初始化
{
if(NULL == s)
{
return FAILURE;
}
*s = (Stack *)malloc(sizeof(Stack));
if(NULL == (*s))
{
return FAILURE;
}
(*s)->data = (int *)malloc(sizeof(int) * SIZE);
if(NULL == (*s)->data)
{
return FAILURE;
}
(*s)->top = -1;
return SUCCESS;
}
int push(Stack *s,int e)
{
if(NULL == s)
{
return FAILURE;
}
if(s->top >= SIZE)
{
return FAILURE;
}
s->data[s->top + 1] = e;
s->top ++;
return SUCCESS;
}
int EmptyStack(Stack *s)
{
if(NULL == s)
{
return FAILURE;
}
return (s->top = -1)? TRUE:FALSE;
}
int GetTop(Stack *s)
{
if(NULL == s)
{
return FAILURE;
}
if(-1 == s->top)
{
return FAILURE;
}
return s->data[s->top];
}
int ClearStack(Stack *s)
{
if(NULL == s)
{
return FAILURE;
}
s->top = -1;
return SUCCESS;
}
int DestoryStack(Stack **s)
{
if(NULL == s)
{
return FAILURE;
}
free((*s)->data);
free(*s);
*s = NULL;
return SUCCESS;
}
主函数 main.c
#include<stdio.h>
#include "SequenceStack.h"
int main()
{
Stack *stack;
int ret;
ret = InitStack(&stack);
if(FAILURE == ret)
{
printf("Init Failure! \n");
}
else
{
printf("Init Success! \n");
}
int i;
for(i = 0; i< 5 ;i ++)
{
ret = push(stack , i + 1);
if(SUCCESS == ret)
{
printf("push Success! \n");
}
else
{
printf("push Failure! \n");
}
}
ret = EmptyStack(stack);
if(ret == TRUE)
{
printf("Stack is empty! \n");
}
else
{
printf("Stack is not empty");
}
ret = GetTop(stack);
if(FAILURE == ret)
{
printf("Get FAILURR! \n");
}
else
{
printf("top is %d \n",ret);
}
for(i = 0 ; i < 3 ; i ++)
{
ret = pop(stack);
if(FAILURE == ret)
{
printf("pop faliure! \n");
}
else
{
printf("pop %d success! \n",ret);
}
}
ret = ClearStack(stack);
if(SUCCESS == ret)
{
printf("Clear Success! \n");
}
else
{
printf("Clear Failure! \n");
}
ret = DestoryStack(&stack);
if(FAILURE == ret)
{
printf("Destory Failure! \n");
}
else
{
printf("Destory Success! \n");
}
for(i = 0 ; i < 3; i ++)
{
ret =push(stack, i+1);
if(FAILURE == ret)
{
printf(" push failure! \n");
}
else
{
printf("push %D success! \n",ret);
}
}
return 0;
}
栈的排序
#include<stdio.h>
#include<stdlib.h>
#include"SequenceStack.h"
int main()
{
Stack *s1,Stack *s2;
int ret,num, i;
if(InitStack(&s1) != SUCCESS || InitStack(&s2) != SUCCESS)
{
printf("Init Failure! \n");
exit(1);
}
for(i = 0; i < SIZE; i ++ )
{
scanf("%d", &um);
if(i == 0)
{
push(s1,num);
}
else
{
while(num < GetTop(s1) && EmptyStack(s1) != TRUE)
{
push(s2,pop(s1));
}
push(s1,num);
while(EmptyStack(s2) != TRUE)
{
push(s1,pop(s2));
}
}
}
for(i = 0 ; i < SIZE ; i ++)
{
printf("%d",pop(s1));
}
printf("\n");
return 0;
}