1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
| #include<stdio.h> #include<stdlib.h> #define MAXN 1000 #define maxsize 5 typedef int Elementtype; typedef struct LNode *Stack; struct LNode{ Elementtype Data[MAXN]; int Top; };
Stack CreateStack(); int Isempty(Stack S); int IsFull(Stack S); void Push(Stack S,Elementtype item); Elementtype Pop(Stack S); void Print(Stack S);
Stack CreateStack() { Stack S; S = (Stack)malloc(sizeof(struct LNode)); S->Top = -1; return S; } void Push(Stack S,Elementtype item) { if(IsFull(S)){ printf("栈满\n"); return ; } S->Top ++ ; S->Data[S->Top] = item; } int IsFull(Stack S) { return (S->Top == maxsize-1); } int Isempty(Stack S) { return (S->Top == -1); } Elementtype Pop(Stack S) { if(Isempty(S)) { printf("栈空\n"); return -1; }else{ Elementtype val = S->Data[S->Top]; S->Top--; return val; } } void Print(Stack S) { int i; printf("栈内元素有: "); for (i = S->Top; i >= 0; i--) { printf("%d ", S->Data[i]); } printf("\n"); }
int main() { Stack S; S = CreateStack(); printf("5入栈\n"); Push(S,5); printf("\n"); Print(S); printf("7入栈\n"); Push(S,7); printf("\n"); Print(S); printf("66入栈\n"); Push(S,66); printf("\n"); Print(S); printf("99入栈\n"); Push(S,99); Print(S); printf("\n"); printf("100入栈\n"); Push(S,100); Print(S); printf("\n"); printf("110入栈\n"); Push(S,110); Print(S); printf("\n"); printf("%d出栈\n",Pop(S)); Print(S); printf("\n"); printf("%d出栈\n",Pop(S)); Print(S); printf("\n"); printf("%d出栈\n",Pop(S)); Print(S); printf("\n"); printf("%d出栈\n",Pop(S)); Print(S); printf("\n"); printf("%d出栈\n",Pop(S)); Print(S); printf("\n"); printf("%d出栈\n",Pop(S)); Print(S); printf("\n"); printf("%d出栈\n",Pop(S)); Print(S); printf("\n"); return 0; }
|