数据结构——栈

来源:互联网 发布:爱奇艺会员淘宝关键字 编辑:程序博客网 时间:2024/06/05 15:25
#include <stdio.h>


#define STACK_SIZE 100
#define OK        0   
#define ERROR    -1  


typedef int DATATYPE;
typedef struct
{
DATATYPE data[STACK_SIZE]; // 栈数组
int top;                   // 栈顶下标
}SeqStack;


// 置空栈
int InitStack (SeqStack *s)
{
if (s == NULL)
{
return ERROR;
}

s->top = -1;

return OK;
}


// 判断空栈
int StackEmpty(SeqStack *s)
{
if (s == NULL)
{
return ERROR;      // 错误返回-1  
}

return s->top == -1;   // 相等返回1 不相等返回0
}


// 判断满栈
int StackFull(SeqStack *s)
{
if (s == NULL)
{
return ERROR;
}

return s->top == STACK_SIZE-1;
}


// 压栈
int Push(SeqStack *s, DATATYPE data)
{
if (s == NULL)
{
return ERROR;
}
// 判断是否满栈
if (StackFull(s))
{
return ERROR;
}

/* s->top++;
s->data[s->top] = data; */
s->data[++s->top] = data;

return OK;
}


// 出栈
int Pop(SeqStack *s)
{
if (s == NULL)
{
return ERROR;
}

// 判断是否空栈
if (StackEmpty(s))
{
return ERROR;
}

DATATYPE data = s->data[s->top--];

return data;
}


// 获取栈顶元素
int GetTop(SeqStack *s)
{
if (s == NULL)
{
return ERROR;
}

// 判断是否空栈
if (StackEmpty(s))
{
return ERROR;
}

return s->data[s->top];;
}


int main()
{
SeqStack stack;   // 栈结构体变量
if (InitStack(&stack) != OK)
{
return -1;
}

if (StackEmpty(&stack))
{
printf ("是空栈\n");
}
else
{
printf ("不是空栈\n");
}

int i;
for (i=0; i<10; i++)
{
if(Push (&stack, i) != OK)
{
return -1;
}
}

if (StackEmpty(&stack))
{
printf ("是空栈\n");
}
else
{
printf ("不是空栈\n");
}

for (i=0; i<10; i++)
{
printf ("%4d", Pop(&stack));
}

if (StackEmpty(&stack))
{
printf ("是空栈\n");
}
else
{
printf ("不是空栈\n");
}


    return 0;
}
原创粉丝点击