生活随笔
收集整理的這篇文章主要介紹了
栈在表达式计算过程中的应用
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
棧在表達(dá)式計(jì)算過(guò)程中的應(yīng)用 :建立操作數(shù)棧和運(yùn)算符棧。運(yùn)算符有優(yōu)先級(jí)。
規(guī)則:
自左至右掃描表達(dá)式,凡是遇到操作數(shù)一律進(jìn)操作數(shù)棧。
當(dāng)遇到運(yùn)算符時(shí),如果它的優(yōu)先級(jí)比運(yùn)算符棧棧頂元素的優(yōu)先級(jí)高就進(jìn)棧。反之,取出棧頂運(yùn)算符和操作數(shù)棧棧頂?shù)倪B續(xù)兩個(gè)操作數(shù)進(jìn)行運(yùn)算,并將結(jié)果存入操作數(shù)棧,然后繼續(xù)比較該運(yùn)算符與棧頂運(yùn)算符的優(yōu)先級(jí)。
左括號(hào)一律進(jìn)運(yùn)算符棧,右括號(hào)一律不進(jìn)運(yùn)算符棧,取出運(yùn)算符棧頂運(yùn)算符和操作數(shù)棧頂?shù)膬蓚€(gè)操作數(shù)進(jìn)行運(yùn)算,并將結(jié)果壓入操作數(shù)棧,直到取出左括號(hào)為止。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100enum link{PUSH, PUSH_NO};typedef struct
{
int num[MAX];
int top;
}OP_num;typedef struct
{
char str[MAX];
int top;
}OP_ch;
void SETNULL_num (OP_num* s)
{s->top = -
1;
}
void SETNULL_ch (OP_ch* s)
{s->top = -
1;
}
int is_num (
char ch)
{
if (ch >=
'0' && ch <=
'9'){
return 1;}
else{
return 0;}
}
int PUSH_num (OP_num *s,
int data)
{
if ((MAX -
1) == s->top){
return 0;}
else{ s->num[++s->top] = data;}
}
int PUSH_ch (OP_ch* s,
char ch)
{
if ((MAX -
1) == s->top){
return 0;}
else{s->
str[++s->top] = ch;}
}
int jud (OP_ch* s,
char ch)
{
if (-
1 == s->top) {
return PUSH;}
else{
switch (s->
str[s->top]) {
case '+':
case '-':{
if (ch ==
'+' || ch ==
'-' || ch ==
')'){
return PUSH_NO;}
else{
return PUSH;}
break;}
case '*':
case '/':{
if (
'(' == ch){
return PUSH;}
else{
return PUSH_NO;}
break;}
case '(':{
return PUSH;
break;}}}
}
int Pop_num (OP_num* s)
{
return (s->num[s->top--]);
}
void Pop_ch (OP_ch* s)
{s->top--;
}
void operate (OP_ch* s_ch, OP_num* s_sum)
{
int a = Pop_num(s_sum);
int b = Pop_num(s_sum);
int result;
switch (s_ch->
str[s_ch->top]){
case '+':result = a + b;
break;
case '-':result = b - a;
break;
case '*':result = a * b;
break;
case '/':result = b / a;
break;} PUSH_num (s_sum, result);
}
int main()
{OP_num sdata;OP_ch soper;SETNULL_num (&sdata);SETNULL_ch (&soper);
int i =
0, len_str, t;
char str[MAX];
char str_num[MAX]; gets (
str); len_str = strlen (
str);
while (
str[i] !=
'\0') {
if (is_num(
str[i])) {t =
0;
while (is_num(
str[i])){str_num[t++] =
str[i++];}str_num[t] =
'\0';PUSH_num (&sdata, atoi(str_num));}
else{
if (PUSH == jud(&soper,
str[i])){PUSH_ch (&soper,
str[i]);}
else{
if (
str[i] !=
')') {operate (&soper, &sdata); Pop_ch(&soper); PUSH_ch (&soper,
str[i]); }
else {do{operate (&soper, &sdata);Pop_ch (&soper);}
while (soper.
str[soper.top] !=
'(');Pop_ch (&soper);}}i++;}}
while (soper.top != -
1){operate (&soper, &sdata);Pop_ch (&soper);}printf (
"%d\n", sdata.num[sdata.top]);
return 0;
}
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)
總結(jié)
以上是生活随笔為你收集整理的栈在表达式计算过程中的应用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。