【中缀表达式转后缀表达式】
#include<iostream>
#include<string>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<ctype.h>
using namespace std;
const int maxn = 1000 + 10;
typedef char TypeName;
struct node {
TypeName num;
struct node *next;
};
typedef struct node Link;
static Link *head;
int isEmpty()
{
return head == NULL;
}
void StackInit()
{
head = NULL;
}
Link * NEW(TypeName num, Link *head)
{
Link *t = (Link *)malloc(sizeof(Link));
t->num = num;
t->next = head;
return t;
}
void StackPush(TypeName num)
{
head = NEW(num, head);
}
TypeName StackPop()
{
TypeName num = head->num;
Link *t = head->next;
free(head);
head = t;
return num;
}
int main()
{
string str;
while (cin >> str)
{
int len = str.length();
for (int i = 0;i < len;i++)
{
char ch = str[i];
if (ch == '(') continue;
if (isdigit(ch)) cout << ch << " ";
else if (ch == ')') cout << StackPop();
else
StackPush(ch);
}
cout << endl;
}
system("pause");
return 0;
}
【后缀表达式求值】
int main()
{
char str[maxn];
while (cin >> str)
{
int len = strlen(str);
StackInit();
for (int i = 0;i < len;i++)
{
char ch = str[i];
if (ch == '*') StackPush(StackPop() * StackPop());
if (ch == '+') StackPush(StackPop() + StackPop());
if (isdigit(ch))
StackPush(0);
while (isdigit(str[i]))
StackPush(StackPop() * 10 + str[i++] - '0');
}
cout << StackPop() << endl;
}
system("pause");
return 0;
}