C语言程序设计 清华大学郑莉安颖莲 栈的应用举例—; 行编辑程序 接收用户输入的程序或数据,存入用户的数据区 “#”表示退格符,“@”表示退行符。 void LineEdit() InitStack(S); ch=getchar ( while (ch!=EOF) while(ch!=EOF &ch!='\n') switch (ch) case '#Pop(S,c); case @'ClearStack(S); default:Push(S,ch); ch=getchar ( ClearStack(S); if(ch!=EOF)ch=getchar(); DestroyStack(S); Page 6
C语言程序设计 清华大学 郑莉 安颖莲 Page 6 栈的应用举例——行编辑程序 • 接收用户输入的程序或数据,存入用户的数据区 “#”表示退格符,“@”表示退行符。 void LineEdit() { InitStack(S); ch=getchar(); while(ch!=EOF) { while(ch!=EOF && ch!='\n') { switch (ch) { case '#':Pop(S,c); case '@':ClearStack(S); default:Push(S,ch); } ch=getchar(); } ClearStack(S); if(ch!=EOF) ch=getchar(); } DestroyStack(S); }
C语言程序设计 清华大学郑莉安颖莲 栈的应用举例 表达式求值 OperandType EvaluateExpression() case'=': { Pop(OPTR,x); InitStack(OPTR);InitStack (OPND); c=getchar ( Push (OPTR,'#')c=getchar(); break; while(c!=#GetTop (OPTR)!='#') case'>': if(!In(c,OP)) Pop(OPTR,theta); Push((OPND,c);c=getchar();} Pop(OPND,b); else Pop(OPND,a); switch(Precede (GetTop(OPTR),c) Push (OPND, case'<': Operate(a,theta,b)); Push (OPTR,c);c=getchar(); break; break; 例1 Page 7
C语言程序设计 清华大学 郑莉 安颖莲 Page 7 栈的应用举例——表达式求值 OperandType EvaluateExpression() { InitStack(OPTR); InitStack(OPND); Push(OPTR,'#'); c=getchar(); while(c!='#'||GetTop(OPTR)!='#') { if(!In(c,OP)) { Push((OPND,c); c=getchar();} else switch(Precede(GetTop(OPTR),c) { case'<': Push(OPTR,c); c=getchar(); break; case'=': Pop(OPTR,x); c=getchar(); break; case'>': Pop(OPTR,theta); Pop(OPND,b); Pop(OPND,a); Push(OPND, Operate(a,theta,b)); break; } } 例 } 1