C堆栈实现的表达式求值
//Luangeng #include<stdio.h> #include<conio.h> #include<windows.h> #define SIZE 100 char t[10][14]={0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,1,0,1,1,1,0,1,1,1,1,1,0, 0,1,1,1,1,0,1,1,1,0,1,0,1,0, 0,0,0,1,0,0,1,0,1,0,0,1,1,0, 0,1,1,1,1,1,0,1,0,1,1,0,1,0, 0,1,0,1,0,1,0,1,1,1,0,1,0,0, 0,1,1,0,1,0,1,0,0,1,1,0,1,0, 0,1,0,1,1,1,0,1,1,1,1,1,0,0, 0,1,1,1,0,1,1,1,0,1,0,1,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0}; typedef struct { short x,y; short d; } step; typedef struct { step *top,*base; } stack; void gotoxy(int x,int y) { COORD cd; cd.X = x; cd.Y = y; HANDLE hout=GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleCursorPosition(hout,cd); } void creat(stack *s) { s->base=(step *)malloc(SIZE*sizeof(step)); s->top=s->base; if(!s->base) printf("failed !\n"); } void push(stack *s,short a,short b,short c) { if(s->top>=(s->base+SIZE)) printf("stack full !.........."); else { s->top++; s->top->x=a; s->top->y=b; s->top->d=c; gotoxy(b,a); printf("%c",1); } } void pop(stack *s) { if(s->base==s->top) printf("\nunderflow....\n"); else { gotoxy(s->top->y,s->top->x); printf(" "); s->top--; } } int main() { stack path; short i,j,k; creat(&path); for(i=1;i<=10;i++) for(j=1;j<=14;j++) { gotoxy(j,i); if(t[i-1][j-1]==0) printf("%s","#"); else printf(" "); } k=1; push(&path,2,2,4); t[1][1]=-1; while(!(path.top->x==9&&path.top->y==13)) { switch(path.top->d) { case 4: path.top->d--; if(t[path.top->x-2][path.top->y-1]==1) { t[path.top->x-2][path.top->y-1]=-1; push(&path,path.top->x-1,path.top->y,4); k++; } break; case 3: path.top->d--; if(t[path.top->x-1][path.top->y]==1) { t[path.top->x-1][path.top->y]=-1; push(&path,path.top->x,path.top->y+1,4); k++; } break; case 2: path.top->d--; if(t[path.top->x][path.top->y-1]==1) { t[path.top->x][path.top->y-1]=-1; push(&path,path.top->x+1,path.top->y,4); k++; } break; case 1: path.top->d--; if(t[path.top->x-1][path.top->y-2]==1) { t[path.top->x-1][path.top->y-2]=-1; push(&path,path.top->x,path.top->y-1,4); k++; } break; case 0: pop(&path); k--; break; } if(path.top==path.base) { gotoxy(17,1); printf("No way out !!"); break; } sleep(5); gotoxy(17,10); printf("step=%d; ",k); } system("pause"); }