Balance(Stack)
栈的运用
#include <iostream> using namespace std; char S[100]; int Top, Number_of_Items = 0; void Push(char c) { if ( Number_of_Items == 0 ) { Top = 0; S[0] = c; } else { Top++; S[Top] = c; } Number_of_Items++; } void Pop() { Top--; Number_of_Items--; } char TopItem() { return S[Top]; } int IsEmpty() { if ( Number_of_Items == 0 ) return 1; else return 0; } int main() { char input; printf("Enter a paretheses sequence (type <Enter> when done) : "); /*solve problem*/ scanf("%c", &input); while ( input != '\n' ) { if ( input == '(' || input == '{' || input == '[' ) Push(input); else if ( input == ')' ) { if( IsEmpty() || TopItem() != '(' ) { printf("This sequence is not balance!\n"); return 0; } else Pop(); } else if ( input == ']' ) { if( IsEmpty() || TopItem() != '[' ) { printf("This sequence is not balance!\n"); return 0; } else Pop(); } else if ( input == '}' ) { if( IsEmpty() || TopItem() != '{' ) { printf("This sequence is not balance!\n"); return 0; } else Pop(); } scanf("%c", &input); } if ( IsEmpty() ) printf("Balanced!\n"); else printf("Not Balance!\n"); return 0; }
永远渴望,大智若愚(stay hungry, stay foolish)