Skip to content

Instantly share code, notes, and snippets.

@limboinf
Created December 23, 2016 09:46
Show Gist options
  • Save limboinf/b0df6fdfa366e33d964a691b56099e08 to your computer and use it in GitHub Desktop.
Save limboinf/b0df6fdfa366e33d964a691b56099e08 to your computer and use it in GitHub Desktop.
数据结构:顺序栈
#include <stdio.h>
#include "global.h"
/*
* ADT 栈(stack)
* InitStack(*S) // 初始化一个空栈S
* DestoryStack(*S) // 若栈存在则销毁
* ClearStack(*S) // 将栈清空
* StackEmpty(S) // 是否为空
* GetTop(S, *e) // 若栈存在且非空则用e返回S的栈顶元素
* Push(*S, e) // 入栈
* Pop(*S, *e) // 出栈
* StackLength(L) // 元素个数
*/
#define MAXSIZE 10
typedef int SElemType;
typedef struct {
SElemType data[MAXSIZE];
int top;
}SqStack;
Status InitStack(SqStack *S)
{
S->top = -1;
return OK;
}
Status ClearStack(SqStack *S) // 设置top即可
{
S->top = -1;
return OK;
}
int StackEmpty(SqStack S)
{
return S.top == -1;
}
Status GetTop(SqStack S, SElemType *e)
{
if (!StackEmpty(S)) {
*e = S.data[S.top];
return OK;
}
return ERROR;
}
Status StackLength(SqStack S)
{
int len = 0;
while (S.top > -1)
{
len++;
S.top--;
}
return len;
}
Status Push(SqStack *S, SElemType e)
{
if(S->top == MAXSIZE - 1) return ERROR; // 栈满
S->top++;
S->data[S->top] = e;
return OK;
}
Status Pop(SqStack *S, SElemType *e)
{
if(S->top == -1) return ERROR; // 栈空
*e = S->data[S->top];
S->top--;
return OK;
}
Status StackTraverse(SqStack S)
{
int i = 0;
while (i <= S.top) {
printf("%d ", S.data[i++]);
}
printf("\n");
return OK;
}
int main(int argc, char **argv)
{
int j;
SqStack S;
if(InitStack(&S) == OK)
for (j = 0; j < 10; ++j) {
Push(&S, j);
}
printf("Stack datas: ");
StackTraverse(S);
int e;
Pop(&S, &e);
printf("Pop的栈顶元素 e=%d\n", e);
Pop(&S, &e);
printf("Pop的栈顶元素 e=%d\n", e);
printf("栈是否为空: %d(1:空,0:否)\n", StackEmpty(S));
GetTop(S, &e);
printf("栈顶元素 e=%d 栈的长度为:%d\n", e, StackLength(S));
ClearStack(&S);
printf("清空栈后,栈空否:%d(1:空 0:否)\n", StackEmpty(S));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment