
好像寫過很多關于后綴運算式的,又好像沒有寫過 ,就記錄下這次的中綴轉后綴,
這道題主要是關于字串的輸入這個老問題,先定義一個字串陣列,然后直接gets()就可以了,長度用strlen()計算 ,用指標來存盤生成的后綴運算式,要注意申請空間,輸出是用%c而不是%s,還要注意格式,下面看原始碼:
#include <bits/stdc++.h>
using namespace std;
int main()
{
char data[1000];
gets(data); //字串輸入方法
char *hou = (char *)malloc(sizeof(char)); //定義指標變數存盤后綴運算式
stack<char> s;
int index = 0;
int length = strlen(data);
for (int i = 0; i < length; i++)
{
if (data[i] >= '0' && data[i] <= '9')
{
hou[index++] = data[i];
}
else if (data[i] == ')')
{
while (!s.empty() && s.top() != '(')
{
hou[index++] = s.top();
s.pop();
}
s.pop();
}
else if(data[i]=='('){
s.push(data[i]);
}
else
{
if(data[i]=='/'||data[i]=='*')
s.push(data[i]);
if(data[i]=='+'||data[i]=='-'){
while(s.top()=='/'||s.top()=='*'){
hou[index++] = s.top();
s.pop();
}
s.push(data[i]);
}
}
}
while (!s.empty())
{
hou[index++] = s.top();
s.pop();
}
printf("%c",hou[0]);
for(int i=1;i<index-1;i++)
printf(" %c", hou[i]);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/287460.html
標籤:其他
上一篇:回應式web-mqtt應用
