学习笔记之数据结构篇-03顺序栈

来源:互联网 发布:淘宝cf得抽奖在那抽的 编辑:程序博客网 时间:2024/05/13 21:27
/*顺序栈的简要实现 * * */#include <stdio.h>  #include <stdlib.h>  #define MAXSIZE 20struct Node;typedef struct Node* PtrToStack;typedef PtrToStack Stack;typedef int ElementType;struct Node{ElementType data[MAXSIZE];int top;};Stack InitStack();/*初始化栈*/void ClearStack(Stack S);/*清空一个栈*/void StackEmpty(Stack S);/*检查栈是否为空*/int GetPop(Stack S);/*返回栈顶元素*/int Push(Stack S, ElementType e);/*压栈操作*/int Pop(Stack S);/*弹栈操作*/int StackLength(Stack S);/*返回栈长度*//*初始化栈*/Stack InitStack(){Stack S = malloc(sizeof(struct Node));S->top = -1;return S;}/*清空一个栈*/void ClearStack(Stack S){S->top = -1;}/*检查栈是否为空*/void StackEmpty(Stack S){if (S->top == -1)printf("栈为空\n");elseprintf("栈非空\n");}/*返回栈顶元素*/int GetPop(Stack S){if (S->top < 0)return NULL;return S->data[S->top];}/*压栈操作*/int Push(Stack S, ElementType e){if (S->top == MAXSIZE - 1)return 0;S->top++;S->data[S->top] = e;return e;}/*弹栈操作*/int Pop(Stack S){ElementType e;if (S->top == -1)return;e = S->data[S->top];S->top--;return e;}/*返回栈长度*/int StackLength(Stack S){return S->top + 1;}void main(){Stack S;S = InitStack();/*初始化栈S*/printf("执行Push操作后(由底至顶):\n");for (int i = 1; i <= 10; i++){printf("%d\n",Push(S, i));}printf("栈顶元素为:%d\n", GetPop(S));printf("栈的长度为:%d\n", StackLength(S));StackEmpty(S);printf("\n");printf("执行Pop操作后(由顶至底):\n");for (int i = 10; i > 0; i--){printf("%d\n",Pop(S));}printf("栈的长度为:%d\n", StackLength(S));printf("栈顶元素为:%d\n", GetPop(S));StackEmpty(S);}

0 0