栈:限定仅在表尾进行插入或删除操作的线性表。 特点:先进后出(last in first out)LIFO
实现:
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 typedef struct SqStack{ char *base; char *top; int stacksize; }SqStack; int InitStack(SqStack &S); int DestroyStack(SqStack &S); int ClearStack(SqStack &S); int StackEmpty(SqStack &S); int StackLength(SqStack S); int GetTop (SqStack &S,char &e); int Push(SqStack &S,char &e); int Pop(SqStack &S,char &e); int StackTraverse(SqStack S); int InitStack(SqStack &S){ S.base = (char *) malloc (STACK_INIT_SIZE * sizeof(char)); if (!S.base) exit (-1 ); S.top = S.base; S.stacksize = STACK_INIT_SIZE; return 1 ; } int GetTop(SqStack &S,char &e){ if (S.top == S.base) return -1 ; e = *(S.top -1 ); return 1 ; } int push(SqStack &S,char &e){ if (S.top - S.base >= S.stacksize){ S.base = (char *) realloc(S.base,(S.stacksize + STACKINCREMENT)*sizeof(char)); if (!S.base) exit (-1 ); S.top = S.base + S.stacksize; S.stacksize += STACKINCREMENT; } *S.top++ = e; return 1 ; } int Pop(SqStack &S,char &e){ if (S.top == S.base) return -1 ; e = *--S.top; return 1 ; } int StackLength(SqStack S){ return S.top - S.base; } int StackTraverse(SqStack S){ char ch; for (int i = 0 ;i < StackLength(S);i++){ ch = *(S.top - 1 - i); printf ("%c " ,ch); } return 1 ; } int StackEmpty(SqStack &S){ if (S.top == S.base){ return 1 ; } else return 0 ; } int ClearStack(SqStack &S){ S.top = S.base; } int DestroyStack(SqStack &S){ free(S.base); S.base = NULL; S.top = NULL; S.stacksize = 0 ; return 1 ; } int main (){ int n; char ch; int i; SqStack S; InitStack(S); char a[5 ]={'a' ,'b' ,'c' ,'d' ,'e' }; for ( i = 0 ; i < 5 ; ++i) { push(S,a[i]); } StackTraverse(S); printf ("\n" ); printf ("%d" ,StackLength(S)); printf ("\n" ); /*清空栈*/ while ( !StackEmpty(S) ){ Pop(S,ch); printf ("%c " ,ch); } return 0 ; }