代码段如下:
头文件:
#ifndef _SEQUENCESTACK_H
#define _SEQUENCESTACK_H
#define Success 10000
#define Failure 10001
#define SIZE 10
typedef int Element;
struct stack
{
int top;
Element *stack;
};
typedef struct stack SK;
int StackInit(SK **s);
int StackEmpty(SK *s);
int StackClear(SK *s);
int GetElement(SK *s);
int StackDistroy(SK **s);
#endif
功能函数:
#include <stdlib.h>
#include "SequenceStack.h"
int StackInit(SK **s)
{
*s = (SK *)malloc(sizeof(SK) * 1);
if(*s == NULL)
{
return Failure;
}
(*s)->top = -1;
(*s)->stack = (Element *)malloc(sizeof(Element) * 10);
if((*s)->stack == NULL)
{
return Failure;
}
return Success;
}
int StackEmpty(SK *s)
{
return (s->top == -1) ? Success : Failure;
}
int StackInsert(SK *s, Element e)
{
if(s == NULL || s->top == 9)
{
return Failure;
}
s->stack[s->top + 1] = e;
s->top++;
return Success;
}
int GetElement(SK *s)
{
if(s == NULL || s->top == -1)
{
return Failure;
}
return s->stack[s->top];
}
int Pop(SK *s)
{
if(s == NULL)
{
return Failure;
}
s->top--;
return Success;
}
int StackClear(SK *s)
{
if(s == NULL)
{
return Failure;
}
s->top = -1;
return Success;
}
int StackDistroy(SK **s)
{
if(s == NULL || *s == NULL)
{
return Failure;
}
free((*s)->stack);
free(*s);
*s = NULL;
return Success;
}
主函数代码段如下:
#include <stdio.h>
#include "SequenceStack.h"
int main()
{
int ret;
SK *stack;
ret = StackInit(&stack);
if(ret == Failure)
{
printf("Init failure!\n");
}
else
{
printf("Init success!\n");
}
ret = StackEmpty(stack);
if(ret == Failure)
{
printf("Stack is not Empty!\n");
}
else
{
printf("Stack is Empty!\n");
}
int i;
for(i = 0; i < 10; i++)
{
ret = StackInsert(stack, i + 1);
if(ret == Failure)
{
printf("Insert %d failure!\n", i + 1);
}
else
{
printf("Insert %d success!\n", i + 1);
}
}
Element e;
ret = GetElement(stack);
if(ret == Failure)
{
printf("Get Failure!\n");
}
else
{
printf("Get %d Success!\n", ret);
}
ret = Pop(stack);
if(ret == Failure)
{
printf("Pop Failure!\n");
}
else
{
printf("Pop success!\n");
}
SSS(stack);
ret = GetElement(stack);
if(ret == Failure)
{
printf("Get Failure!\n");
}
else
{
printf("Get %d Success!\n", ret);
}
ret = StackClear(stack);
if(ret == Failure)
{
printf("Clear Failure!\n");
}
else
{
printf("Clear Success!\n");
}
ret = GetElement(stack);
if(ret == Failure)
{
printf("Get Failure!\n");
}
else
{
printf("Get %d Success!\n", ret);
}
ret = StackDistroy(&stack);
if(ret == Failure)
{
printf("Distroy failure!\n");
}
else
{
printf("Distroy success!\n");
}
return 0;
}