眾所周知,計(jì)算機(jī)中不能直接用中綴表達(dá)式計(jì)算,形如(1+2)*(4-5)之類(lèi)的,但是我們可以計(jì)算機(jī)可以很容易的通過(guò)后綴表達(dá)式來(lái)計(jì)算我們所輸入的算式张抄。所以我們就需要把中綴表達(dá)式轉(zhuǎn)換為后綴表達(dá)式耍贾。下面是個(gè)人寫(xiě)的一點(diǎn)代碼苫费,大家可以參考翁狐。
開(kāi)始
添加適當(dāng)?shù)念^文件,定義一個(gè)棧數(shù)據(jù)結(jié)構(gòu)钥飞,
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <ctype.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef char ElemType;
typedef struct
{
ElemType *base;
ElemType *top;
int stackSize;
}SqStack;
創(chuàng)建一個(gè)棧
//創(chuàng)建一個(gè)棧
void initStack(SqStack *s) {
s->base = (ElemType *)malloc(sizeof(ElemType));
if (!s->base)
{
exit(0);
}
s->top = s->base; //最開(kāi)始 棧底就是棧頂
s->stackSize = STACK_INIT_SIZE;
}
入棧操作
void Push(SqStack *s, ElemType e) {
//如果棧滿 追加空間
if (s->top - s->base >= s->stackSize)
{
s->base = (ElemType *)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
if (!s->base)
{
exit(0);
}
s->top = s->base + s->stackSize; //設(shè)置棧頂
s->stackSize = s->stackSize + STACKINCREMENT;
}
*(s->top) = e;
s->top++;
}
出棧操作
void Pop(SqStack *s, ElemType *e) {
if (s->top == s->base)
{
return;
}
*e = *--(s->top);
}
計(jì)算棧的當(dāng)前容量(最大容量是s.stackSize)
int StackLen(SqStack s) {
return (s.top - s.base);
}
主函數(shù)
int main() {
char cal[50];
char c, e;
SqStack s;
initStack(&s);
printf("請(qǐng)輸入中綴表達(dá)式 輸入#表示結(jié)束\n");
scanf_s("%c", &c);
while (c != '#')
{
while (c>='0' && c<='9')
{
printf("%c ", c);
scanf_s("%c", &c);
if (c<'0' || c>'9')
{
printf(" ");
}
}
if (c == ')')
{
Pop(&s, &e);
while (e != '(')
{
printf("%c ", e);
Pop(&s, &e);
}
}
else if (c == '+' || c == '-')
{
if (!StackLen(s))
{
Push(&s, c);
}
else {
do
{
Pop(&s, &e);
if (e == '(')
{
Push(&s, e);
}
else {
printf("%c ", e);
}
} while (StackLen(s) && e!='(');
Push(&s, c);
}
}else if (c=='*' || c=='/' || c=='(')
{
Push(&s, c);
}else if (c=='#')
{
break;
}
else {
printf("出錯(cuò)莺掠,輸入格式錯(cuò)誤");
return -1;
}
scanf_s("%c", &c);
}
while (StackLen(s))
{
Pop(&s, &e);
printf("%c ", e);
}
return 0;cd
}
以下是運(yùn)行結(jié)果 本人用的是vs2015編譯器,所以文中的scanf用了更安全的scanf_s读宙, 如有引用 請(qǐng)自覺(jué)替換成和自己的編譯器想匹配的函數(shù)
cmd 運(yùn)行結(jié)果
代碼很簡(jiǎn)單 彻秆,仔細(xì)看看研究一下指針就很容易看懂,
注:
- 上述代碼在visual studio 2015中編譯成功運(yùn)行,其他ide請(qǐng)自行測(cè)試
- 上述文字皆為個(gè)人看法唇兑,如有錯(cuò)誤或建議請(qǐng)及時(shí)聯(lián)系我