1.栈的顺序存储
#include<stdio.h>#include<stdlib.h>#define MaxSize 100typedef int ElementType;typedef struct SNode *Stack;struct SNode{ElementType Data[MaxSize];int Top;};Stack S;Stack CreateStack();bool IsFull(Stack S);bool IsEmpty(Stack S);void Push(Stack S,ElementType item);ElementType Pop(Stack S);int main(void){S = CreateStack();printf("5入栈\n");Push(S,5);printf("7入栈\n");Push(S,7);printf("66入栈\n");Push(S,66);printf("44入栈\n");Push(S,44);printf("%d出栈\n",Pop(S));printf("%d出栈\n",Pop(S));printf("%d出栈\n",Pop(S));printf("%d出栈\n",Pop(S));if(IsEmpty(S)){printf("堆栈空");}return 0;}Stack CreateStack(){S = (Stack)malloc(sizeof(struct SNode));S->Top = -1;return S;}bool IsFull(Stack S){return (S->Top == MaxSize-1);}bool IsEmpty(Stack S){return (S->Top == -1);}void Push(Stack S,ElementType item){if(IsFull(S)){printf("堆栈满");return;}else{S->Top++;S->Data[S->Top] = item;return;}}ElementType Pop(Stack S){if(IsEmpty(S)){printf("堆栈空");return -1;}else{ElementType val = S->Data[S->Top];S->Top--;return val;}}
2.栈的链式存储
#include <stdio.h>#include <stdlib.h>struct SNode{int Data;struct SNode *Next;};typedef struct SNode *Stack;Stack S;Stack CreateStack();bool IsEmpty(Stack S);void Push(Stack S,int item);int Pop( Stack S );int main(void){S = CreateStack();printf("5入栈\n");Push(S,5);printf("7入栈\n");Push(S,7);printf("66入栈\n");Push(S,66);printf("44入栈\n");Push(S,44);printf("%d出栈\n",Pop(S));printf("%d出栈\n",Pop(S));printf("%d出栈\n",Pop(S));printf("%d出栈\n",Pop(S));if(IsEmpty(S)){printf("堆栈空");}return 0;}Stack CreateStack(){Stack S;S = (Stack)malloc(sizeof(struct SNode));S->Next = NULL;return S;}bool IsEmpty(Stack S){return (S->Next == NULL);}void Push(Stack S,int item){Stack tmp;tmp = (Stack)malloc(sizeof(struct SNode));tmp->Data = item;tmp->Next = S->Next;S->Next = tmp;}int Pop( Stack S ){Stack Firstcell;int Toptmp;if ( IsEmpty(S) ){printf("栈空\n");return -1;}Firstcell = S->Next;S->Next = Firstcell->Next;Toptmp = Firstcell->Data;free(Firstcell);return Toptmp;}
