鼓捣了一小天,终于把这用数组实现的Stack搞出来了。
我把它试着应用在检查括号是否配对上了,还行,挺好玩的。当然了,bug也不少,只适用括号检查, 使用不当,后果自负:)。
编程收获:
1. 函数声明时type是主要的,至于变量名可有可无。但是调用函数就不要带type了:)。
2.函数要先声明后使用,如果先使用后声明,那么GCC 将其返回值默认为int,如果你后面声明成了void,那么会报错:conflict types。
3.(),[],->优先级最高,结合from left to right。
4. 数组和指针完全可以互换的,使用方法也是可以的。
5. 该死的天气又在下雨了,出门最好带伞:)。
待完善:
1.如果括号不是配对的,要报出出错的地方,即index
2.把backet([]),braces({})包含进来。
//Implement Stack by Array #include <stdio.h> #include <stdlib.h> //include exit(),malloc() function。 #include <string.h> //include strlen function #define EMTPTYSTACK -1 //define the empty stack arry subcript, so the element would be started from array[0] #define MAXELEMENTS 100 struct StackRecord; typedef struct StackRecord *Stack; typedef char ElementType ; //define element type void Error (char input[]) { printf("%s\n",input); exit(4); } struct StackRecord { int Capacity; // record the total space allocated for this stack int TopOfStack; //record the Array subscript of top element ElementType *Array; //record the allocated array address }; int IsEmpty(Stack S); int IsFull(Stack S); void Push(ElementType x, Stack S); void Pop(Stack S); Stack CreateStack(int Maxelement); void MakeEmpty (Stack S); ElementType Top(Stack S); ElementType PopAndTop(Stack S); int IsEmpty (Stack S) { return S->TopOfStack == EMTPTYSTACK; } int IsFull (Stack S) { return S->TopOfStack == S->Capacity-1; //topofstack is ranged from 0 to MAXELEMENTS-1 } void Push(ElementType x, Stack S) { if(IsFull(S)) Error("Out of Space !!!\n"); else S->Array[ ++S->TopOfStack ] = x; } void Pop (Stack S) { if ( IsEmpty( S) ) Error("Empty Stack !!\n"); else S->TopOfStack--; } Stack CreateStack (int Maxelement) { Stack S; S = malloc(sizeof(struct StackRecord)); if (S == NULL) Error("Out of Space !!!\n"); S->Array=malloc(sizeof(ElementType)*Maxelement); if (S->Array == NULL) Error("Out of Space !!!\n"); S->Capacity = Maxelement; MakeEmpty (S); return S; } void MakeEmpty (Stack S) { S->TopOfStack = EMTPTYSTACK; } ElementType Top(Stack S) { return S->Array[S->TopOfStack]; } ElementType PopAndTop(Stack S) { return S->Array[S->TopOfStack--]; //operator precedence of -> (left to right) is higher than --/++ ; } int main (void) { char input_s[]="(((((((((()))))))))"; int i=0; int lengh=strlen(input_s); ElementType ch; Stack Stack_instance; Stack_instance=CreateStack(MAXELEMENTS); for(;i<lengh;i++) { if(input_s[i] == '(') Push(input_s[i],Stack_instance); else { if(Top(Stack_instance) != '(') Error("Parantheses does not come in pair !!\n"); else Pop(Stack_instance); } } if(IsEmpty(Stack_instance)) printf("Good kid, your parentheses come in pair !!\n"); else printf("Damn it ! Your parentheses does not come in pair !!\n"); return 0; }