1 /* 2 栈是限制插入和删除只能在一个位置上进行的表,该位置是表的末端(最后进入栈的元素位置),叫做栈的顶。 3 栈具有后进先出的特点,用链表实现时可采用首插法实现这一特性。 4 对于栈,进栈操作要检查栈是否有空间;出栈和取栈顶值要检查栈是否为空栈。 5 */ 6 7 /*栈的链表实现*/ 8 9 /*接口头文件*/ 10 typedef int ElementType; 11 12 #ifndef _STACK_H 13 #define _STACK_H 14 #include <stdbool.h> 15 16 struct Node; 17 typedef struct Node * PtrToNode; 18 typedef PtrToNode Stack; 19 typedef PtrToNode Position; 20 21 /*操作集*/ 22 bool IsEmpty( Stack S ); 23 Stack CreateStack( void ); 24 void MakeEmpty( Stack S ); 25 void Pop( Stack S ); 26 void Push( ElementType X, Stack S ); 27 ElementType Top( Stack S ); 28 void DisposeStack( Stack S ); 29 void PrintfStack( Stack S ); 30 31 #endif 32 33 34 /*接口实现*/ 35 #include <stdio.h> 36 #include <stdlib.h> 37 #include "stack.h" 38 39 /*特定结构体定义*/ 40 struct Node 41 { 42 ElementType Element; 43 Position Next; 44 }; 45 46 bool IsEmpty( Stack S ) 47 { 48 return S->Next ==NULL; 49 } 50 51 Stack CreateStack( void ) 52 { 53 Stack S; 54 55 S = ( Stack )malloc( sizeof( struct Node ) ); 56 if ( S == NULL ) 57 { 58 printf( "No Space!!! " ); 59 exit( 1 ); 60 } 61 S->Next = NULL; 62 /*确保S是空栈*/ 63 MakeEmpty( S ); 64 65 return S; 66 } 67 68 void MakeEmpty( Stack S ) 69 { 70 Position P; 71 72 if ( S == NULL ) 73 { 74 printf( "No use CreateStack!!! " ); 75 exit( 1 ); 76 } 77 else 78 while ( ! IsEmpty( S ) ) 79 Pop( S ); 80 } 81 82 void Pop( Stack S ) 83 { 84 Position P; 85 86 if ( IsEmpty( S ) ) 87 { 88 printf( "Stack is empty!!! " ); 89 exit( 1 ); 90 } 91 else 92 { 93 P = S->Next; 94 S->Next = S->Next->Next; 95 free( P ); 96 } 97 } 98 99 void Push( ElementType X, Stack S ) 100 { 101 Position P; 102 103 P = ( Stack )malloc( sizeof( struct Node ) ); 104 if ( P == NULL ) 105 { 106 printf( "No Space!!! " ); 107 exit( 1 ); 108 } 109 else 110 { 111 P->Element = X; 112 P->Next = S->Next; 113 S->Next = P; 114 } 115 } 116 117 ElementType Top( Stack S ) 118 { 119 if ( IsEmpty( S ) ) 120 { 121 printf( "Stack is empty!!! " ); 122 exit( 1 ); 123 } 124 else 125 return S->Next->Element; 126 } 127 128 void DisposeStack( Stack S ) 129 { 130 /* 131 Position P; 132 133 while ( S->Next != NULL ) 134 { 135 P = S->Next; 136 S->Next = S->Next->Next; 137 free( P ); 138 } 139 */ 140 MakeEmpty( S ); 141 /*释放栈头*/ 142 free( S ); 143 } 144 145 /*打印栈,且把栈变为空栈*/ 146 void PrintfStack( Stack S ) 147 { 148 while ( ! IsEmpty( S ) ) 149 { 150 printf( "%3d", Top( S ) ); 151 Pop( S ); 152 } 153 printf( " " ); 154 } 155 156 157 //平衡符号,检查输入的算式是否正确只检查{},(),[]三种,例如(a+b){[d]c*d}{}是正确的,但是(a+b){{[d]c*d}{}不对 158 void balance(char * ch, Stack S) 159 { 160 ElementType c; 161 MakeEmpty(S); 162 while ((c = *ch) != '