**
順序棧可以用一個一維數組和一個記錄棧頂位置的整形變量來實現,數組用于順序存儲棧中所有的數據元素,棧頂指針用于存儲棧頂元素的位置。
**
頭文件(Sqstack.h):
#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);#endif
源文件(Sqstack.c):
#include "SqStack.h"// 置空棧
int InitStack (Stack* s)
{if (NULL == s){errno = ERROR;return FALSE;}s->top = -1;
}// 空返回真,否則返回假
int StackEmpty (Stack* s)
{if (NULL == s){errno = ERROR;return FALSE;}return s->top == -1;
}// 滿則返回真,否則返回假
int StackFull (Stack* s)
{if (NULL == s){errno = ERROR;return FALSE;}return s->top == (SIZE - 1);
}// 進棧
int Push (Stack* s, StackData x)
{if (NULL == s){errno = ERROR;return FALSE;}// 判斷是否棧滿if (StackFull(s)){errno = FULL_STACK;return FALSE;}// 先進行x的存儲s->data[++s->top] = x; return TRUE;
}// 出棧
int Pop (Stack* s, StackData *x)
{if (NULL == s){errno = ERROR;return FALSE;}// 判斷是否空棧if (StackEmpty(s)){errno = EMPTY_STACK;return FALSE;}*x = s->data[s->top--];return TRUE;
}// 取棧頂
int GetTop (Stack* s, StackData *x)
{if (NULL == s){errno = ERROR;return FALSE;}//判斷是否空棧if (StackEmpty(s)){errno = EMPTY_STACK;return FALSE;}*x = s->data[s->top];return TRUE;
}