C语言程序设计 清华大学郑莉安颖莲 栈的应用举例行编辑程序 接收用户输入的程序或数据,存入用户的数据区 “#”表示退格符,“@”表示退行符。 void LineEdito InitStack(S) ch=getchar while(ch!=EOF) I while(ch!=EOF & ch!='\n') switch(ch case Pop (s, c) case'@': ClearStack(S) default: Push(S, ch) ch=getchar( ClearStack(S f(ch!=EoF) ch=getchar DestroyStack(S
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 o case Pop( optr, x) InitStack(OPTR); InitStack(OPND); c=getchar Push(oPTR, #) c=getchar b reak while(c!=#'GetTop(OPTR)!=#') case I if(!In(c, OP)) Pop(optr, theta) I Push((oPND, c); c=getchar o; Pop (opnd, b) Pop (opnd, a) e⊥se switch(Precede(GetTop(optr), c) Push oPnD Operate(a, theta, b)) case < Push (oPTR, c); c=getchar break break 例1
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