给定入栈出栈顺序判断是否合法,顺序以一维数组给定
int gudge(SqStack *s,ElemType a[8]){ int e; int empty; for(ElemType i=0;i<8;i++){ printf("%d\n",a[i]); empty=StackEmpty1(s); if(a[i]==0){ if(empty==1){return 0;break;} else PopStack(s,e); } else {PushStack(s,1);} } empty=StackEmpty1(s); if(empty==1){return 1;} else return 0;}
栈在括号匹配中的应用
思想:先设置一个空栈,按顺序进栈,如果有匹配项则栈内元素出栈,如果没有就入栈或者出错
void BracketsMatch(SqStack *s,char b[8]){ char e,c; int flag=1; for(int i=0;i<8;i++){ c=b[i]; if(c=='('||c=='{'||c=='['){ PushStack(s,c); } else{ if(GetTop(s)=='['){ if(c==']'){PopStack(s,e);continue;} else{printf("匹配出错1\n");flag=0;break;} } if(GetTop(s)=='('){ if(c==')'){PopStack(s,e);continue;} else{printf("匹配出错2\n");flag=0;break;} } if(GetTop(s)=='{'){ if(c=='}'){PopStack(s,e);continue;} else{printf("匹配出错3\n");flag=0;break;} } } } if(flag==1){printf("匹配成功\n");} else{printf("匹配不成功\n");}}
void main(){ SqStack S; char bra[8]={'{','(','[',']','[',']',')','}'}; InitStack(&S); BracketsMatch(&S,bra);}
栈在表达式求值中的应用
栈求表达式的值用的是后缀表达式,这与后面的二叉树有所不同,后缀表达式:A+B*(C-D)-E/F=ABCD-*+EF/-
void ValueStack(SqStack *s,char ch[11]){ int c1,c2; ElemType e; int a; for(int i=0;i<11;i++){ if(ch[i]<10){PushStack(s,ch[i]);} else{ c1=GetTop(s); PopStack(s,e); c2=GetTop(s); PopStack(s,e); if(ch[i]=='+'){PushStack(s,c1+c2);continue;} if(ch[i]=='-'){PushStack(s,c2-c1);continue;} if(ch[i]=='*'){PushStack(s,c2*c1);continue;} if(ch[i]=='/'){PushStack(s,c2/c1);continue;} } } PrintStack(s);}
void main(){ SqStack S; char c[11]={1,4,5,3,'-','*','+',6,2,'/','-'}; InitStack(&S); ValueStack(&S,c);}
渡口管理模拟:渡船一次可以载10辆车过江,同类车先到先上,客车优先货车上船,每4辆客车上1辆货车,客车不足4辆,货车代替,无货车等待,允许客车都上船
int Manager(LinkQueue *q1,LinkQueue *q2,LinkQueue *q3){ElemType e;if(q2->length==0){while(q1->length!=0){DeQueue(q1,e);EnQueue(q3,e);}PrintQueue(q3);return 1;}//无货车等待,客车全部上船while(q3->length!=10){if(q1->length>=4){for(int i=0;i<4;i++){DeQueue(q1,e);EnQueue(q3,e);}DeQueue(q2,e);EnQueue(q3,e);}//每隔四辆客车后上一辆货车else{for(int i=0;i<q1->length;i++){DeQueue(q1,e);EnQueue(q3,e);}DeQueue(q2,e);EnQueue(q3,e);}//客车不足四辆时用货车补齐}PrintQueue(q3);return 1;}int main(){LinkQueue L1;//客车队列LinkQueue L2;//货车队列LinkQueue L;//渡船队列InitQueue(&L);InitQueue(&L1);InitQueue(&L2);EnQueue(&L1,1);EnQueue(&L1,1);EnQueue(&L1,1);EnQueue(&L1,1);EnQueue(&L1,1);EnQueue(&L2,2);EnQueue(&L2,2);EnQueue(&L2,2);EnQueue(&L2,2);EnQueue(&L2,2);Manager(&L1,&L2,&L);}
转载于:https://www.cnblogs.com/Yshun/p/11166717.html