資源簡介
大一學習了用C語言實現的表達式求值,就是用C語言寫的一個計算器,包括+-*/()等運算,也許你會覺得很簡單,但是我花了很長時間才弄明白,其中用到了棧、隊列等算法。
代碼片段和文件信息
#include
#include
#define?max?100
#define?maxop?6
typedef?struct?node
{
int?date[max];
int?top;??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????;
}sqstack;
sqstack?K;
sqstack?*L*s;
sqstack?*?inistack(sqstack?*?s)
{
s=(sqstack?*)malloc(sizeof(K));
s->top=-1;
return?s;
}
int?stackempty(sqstack?*?s)
{
return(s->top==-1);
}
sqstack?*?push(sqstack?*Lint?i)
{
if(s->top==max-1)
{
printf(“棧滿!“);
return?0;
}
s->top++;
s->date[s->top]=i;
return(L);
}
int?pop(sqstack?*s)
{
int?e;
if(s->top==-1)
{
printf(“棧空!“);
return?0;
}
e=s->date[s->top];
s->top--;
return(e)?;
}
?int?gettop(sqstack?*s)
{
int?e;
if(s->top==-1)
{
printf(“棧空!“);
return?0;
}
e=s->date[s->top];
return(e)?;
}
struct?youxianji
{
char?ch;
int?pri;
}lpri[7]={{‘=‘0}{‘(‘1}{‘*‘5}{‘/‘5}{‘+‘3}{‘-‘3}{‘)‘6}}
?rpri[7]={{‘=‘0}{‘(‘6}{‘*‘4}{‘/‘4}{‘+‘2}{‘-‘2}{‘)‘1}};
?
?int?leftpri(char?op)
{
int?i;
for(i=0;i if(lpri[i].ch==op)
return(lpri[i].pri);
}
?int?rightpri(char?op)
{
int?i;
for(i=0;i if(rpri[i].ch==op)
return(rpri[i].pri);
}
int?inop(char?ch)
{
if(ch==‘(‘||ch==‘)‘||ch==‘+‘||ch==‘-‘||ch==‘*‘||ch==‘/‘)
return(1);
else
return(0);
}
int?outop(char?exc[])
{
????char?*exp=exc;
????while(*?exp!=‘\0‘)
{
????if(*exp==‘(‘||*exp==‘)‘||*exp==‘+‘||*exp==‘-‘||*exp==‘*‘||*exp==‘/‘||(*exp>=‘0‘&&?*exp<=‘9‘))
exp++;
else?
break;
};
if(*exp==‘\0‘)
return(1);
else
{
printf(“輸入表達式錯誤!請重新輸入表達式:\n“);
?return(0);
????}
}
int?precede(char?op1char?op2)
{
if(leftpri(op
評論
共有 條評論