棧順序存儲方式實現
## 0. 棧結構定義
#include "stdio.h"
#include "stdlib.h"
#define MAXSIZE 20
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int Status;
typedef int SElemType;
typedef struct SeqStack{
SElemType data[MAXSIZE];
// 棧頂指針
int top;
}SeqStack;
1. 初始化棧
Status InitStack(SeqStack* stack)
{
stack->top = -1;
return OK;
}
2.判斷棧是否爲空
Status StackEmpty(SeqStack stack)
{
if ( stack.top == -1 )
return TRUE;
else
return FALSE;
}
3. 壓棧操作
Status Push(SeqStack* stack, SElemType e)
{
if (stack->top >= MAXSIZE -1)
return ERROR;
stack->top++;
stack->data[stack->top] = e;
return OK;
}
4. 彈棧操作
Status Pop(SeqStack* stack, SElemType* e)
{
if (stack->top == -1 )
return ERROR;
*e = stack->data[stack->top];
stack->top--;
return OK;
}
5. 獲取棧頂元素
Status GetTop(SeqStack stack, SElemType* e)
{
if (stack.top == -1)
return ERROR;
*e = stack.data[stack.top];
return OK;
}
6. 獲得棧的長度
int StackLength(SeqStack satck)
{
return satck.top + 1;
}
7. 打印棧元素
Status StackTraverse(SeqStack stack)
{
int i;
i=0;
while(i<=stack.top)
{
printf("%d\t",stack.data[stack.top--]);
}
printf("\n");
return OK;
}
8. 清空棧
Status ClearStack(SeqStack* stack)
{
stack->top = -1;
return OK;
}
9. 測試
int main(void)
{
SeqStack stack;
// 初始化棧
InitStack(&stack);
// 向壓棧
Push(&stack,1);
Push(&stack,11);
Push(&stack,111);
printf("The length of Stack is:%d\n",StackLength(stack));
int value;
Pop(&stack,&value);
printf("彈出的元素爲:%d\n",value);
StackTraverse(stack);
return 0;
}