生活随笔
收集整理的這篇文章主要介紹了
数据结构实验之栈与队列三:后缀式求值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Description
對于一個基于二元運算符的后綴表示式(基本操作數都是一位正整數),求其代表的算術表達式的值。
Input
輸入一個算術表達式的后綴式字符串,以‘#’作為結束標志。
Output
求該后綴式所對應的算術表達式的值,并輸出之。
Sample
Input
59684/-3+#
Output
57
Hint
基本操作數都是一位正整數!
規則:
從左到右遍歷表達式的每個數字和字符,遇到數字就進棧,遇到符號,就將處于棧頂的兩個數字出棧,進行運算,運算的結果在進棧,一直到最終獲得結果。
#include<bits/stdc++.h>using namespace std
;#define intsize 100000
#define addsize 100000typedef int elemtype
;typedef struct
{elemtype
*base
;elemtype
*top
;int stacksize
;
} Sqstack
;int initstack(Sqstack
&s
)
{s
.base
= (elemtype
*)malloc(intsize
*sizeof(elemtype
));if(!s
.base
)return -1;s
.top
= s
.base
;s
.stacksize
= intsize
;return 0;
}int push(Sqstack
&s
, elemtype x
)
{if(s
.top
- s
.base
> s
.stacksize
){s
.base
= new elemtype
[intsize
+ addsize
];if(!s
.base
) return -1;s
.top
= s
.base
+ addsize
;s
.stacksize
+= addsize
;}*s
.top
++ = x
;return 0;
}elemtype
pop(Sqstack
&s
)
{elemtype x
;return x
= *--s
.top
;
}void change(Sqstack
&s
, elemtype n
)
{int e1
, e2
;if(n
== '+'){e1
= pop(s
);e2
= pop(s
);push(s
, e1
+ e2
);}else if(n
== '-'){e1
= pop(s
);e2
= pop(s
);push(s
, e2
- e1
);}else if(n
== '*'){e1
= pop(s
);e2
= pop(s
);push(s
, e1
* e2
);}else if(n
== '/'){e1
= pop(s
);e2
= pop(s
);push(s
, e2
/ e1
);}
}void show(Sqstack
&s
)
{while(s
.top
!= s
.base
){printf("%d", pop(s
));}printf("\n");
}int main()
{Sqstack s
;char n
;initstack(s
);while(~scanf("%c", &n
) && n
!= '#'){if(n
>= '0' && n
<= '9'){push(s
, n
- '0');}else{change(s
, n
);}}show(s
);return 0;
}
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀
總結
以上是生活随笔為你收集整理的数据结构实验之栈与队列三:后缀式求值的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。