数据结构顺序栈

时间:2022-05-18 10:28:18

栈(stack)又名堆栈,它是一种运算受限的线性表。其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。向一个栈插入新元素又称作进栈、入栈或压栈,它是把新元素放到栈顶元素的上面,使之成为新的栈顶元素;从一个栈删除元素又称作出栈或退栈,它是把栈顶元素删除掉,使其相邻的元素成为新的栈顶元素。

顺序栈:

#ifndef __SQSTACK_H__
#define __SQSTACK_H__

#include "error.h"

#define TRUE 1
#define FALSE 0

#define SIZE 10
typedef int StackData;
typedef struct _stack
{
StackData data[SIZE]; // 栈数组
int top; // 栈顶元素下标
}Stack;

// 置空栈
int InitStack (Stack *S);

// 判栈是否空栈
int StackEmpty (Stack *S);

// 判栈是否栈满
int StackFull (Stack *S);

// 进栈
int Push (Stack *S, StackData x);

// 出栈
int Pop (Stack *S, StackData *x);

// 取栈顶
int GetTop (Stack *S, StackData *x);

/*
//对象:由数据类型为StackData的元素构成
int Push (stack *S, StackData x);//进栈
int Pop (stack *S, StackData &x); //出栈
int GetTop (stack *S, StackData &x); //取栈顶
void InitStack (stack *S); //置空栈
int StackEmpty (stack *S); //判栈空否
int StackFull (stack *S); //判栈满否
*/

#endif // __SQSTACK_H__
#include "SqStack.h"int InitStack (Stack *S){if (S == NULL){errno = ERROR;return FALSE;}S->top = -1;   }// 空返回真,否则返回假int StackEmpty (Stack *S){if (S == NULL){errno = ERROR;return FALSE;}return S->top == -1;}// 满返回真,否则返回假int StackFull (Stack *s){if (s == NULL){errno = ERROR;return FALSE;}return s->top == (SIZE-1);}int Push (Stack *s, StackData x){if (s == NULL){errno = ERROR;return FALSE;}// 判断是否满栈if (StackFull(s)){errno = FULL_STACK;return FALSE;}/*s->data[top+1] = x;s->top++;*/s->data[++s->top] = x;return TRUE;}int Pop (Stack *s, StackData *x){if (s == NULL){errno = ERROR;return FALSE;}// 判断是否空栈if (StackEmpty(s)){errno = EMPTY_STACK;return FALSE;}/**x = s->data[s->top];s->top--;*/*x = s->data[s->top--];return TRUE;}int GetTop (Stack *s, StackData *x){if (s == NULL){errno = ERROR;return FALSE;}// 判断是否空栈if (StackEmpty(s)){errno = EMPTY_STACK;return FALSE;}*x = s->data[s->top];return TRUE;}
#include <stdio.h>#include "SqStack.h"int main(){Stack s;if (InitStack(&s) == FALSE){printf ("初始化失败\n");printf ("错误号:%d\n", errno);myError("InitStack");char * str = myStrError(errno);printf ("str: %s\n", str);}if (StackEmpty(&s)){printf ("空栈\n");}if (StackFull(&s)){printf ("满栈\n");}int x;if (Pop(&s, &x) != TRUE){myError ("Pop 错误");}int i;for (i = 0; i < 10; i++){Push(&s, i);}if (Push(&s, 100) != TRUE){myError("压入第11个元素");}char str[100];for (i = 0; i < 12; i++){if (Pop (&s, &x) != TRUE){sprintf (str, "Pop第%d个元素", i);myError (str);}printf ("x : %d\n", x);}return 0;}