考研資料結構與演算法之堆疊的使用(三)利用堆疊匹配括號
阿新 • • 發佈:2019-02-07
具體實現方法如下:
注意一個很有意思的問題,在教材中匹配的是括號是[] {}和()而我則不使用()原因是他倆的ASCII碼相差為1而其他的都是2,為了運算方便而進行了簡化。另外還要更正之前對GetTop方法的定義,修改後的該函式如下:int main(void) { SqStack S; InitStack(S); char str[255]; scanf("%s",str); int i = 0; while( str[i] != '\0') { if( (str[i]=='[') | (str[i]=='{') | (str[i]=='<') ) { Push(S, str[i]); }else if( (str[i]==']') || (str[i]=='}') || (str[i]=='>') ) { if(!StackEmpty(S)) { char t; GetTop(S, t); if( t == str[i]-2 ) Pop(S, t); }else break; } i++; } if( StackEmpty(S) && (str[i] == '\0') ) { printf("YES"); }else { printf("NO"); } system("pause"); }
Status GetTop(SqStack &S, SElemType &e)
{
if( S.base == S.top )
return ERROR;
e = *(S.top - 1);
return OK;
}
確實是我疏忽了,由於覺得簡單就忘記了對它進行測試,結果今天使用的時候怎麼也出不來結果。