#include<iostream>
using namespace std;
struct Mystack {
char c;
Mystack* next;
};
struct LinkStack {
Mystack* top;
};
void Create(LinkStack& s) { //栈初始化
s.top = NULL;
}
bool IsEmpty(LinkStack& s) { //判断是否为空
if (s.top == NULL)
return true;
else
return false;
}
void Push(LinkStack&s,char a) { //添加
Mystack *newstack = new Mystack;
newstack->c = a;
newstack->next = s.top;
s.top = newstack;
}
char Pop(LinkStack&s) { //弹出
char c = s.top->c;
s.top = s.top->next;
return c;
}
char MyJudgePop(LinkStack s) { //返回栈定元素的值
char c = s.top->c;
return c;
}
void Display(LinkStack&s) { //显示栈中元素
Mystack* p = s.top;
while (p!= NULL) {
cout << p->c << " ";
p = p->next;
}
cout << endl;
}
int Judge(char c) { //判断字符类型
if (c>=97&&c<=122)
return 0;
else if (c == '+' || c == '-')
return 1;
else if (c == '*' || c == '/')
return 2;
else if (c == '(')
return 3;
else if (c == ')')
return 4;
else
return 5;
}
int main() {
LinkStack s;
Create(s);
LinkStack s1;
Create(s1);
while (1) {
cout << "请输入字符:" << endl;
char c;
cin >> c;
int a = Judge(c);
if (a == 0) {
Push(s1, c);
}
else if (a == 1) {
if (IsEmpty(s)) {
Push(s, c);
}
else if (MyJudgePop(s)=='(') {
Push(s, c);
}
else if (MyJudgePop(s) != '(') {
while (1) {
if (IsEmpty(s)) {
break;
}
if (MyJudgePop(s) == '(') {
break;
}
char c2 = Pop(s);
Push(s1, c2);
}
Push(s, c);
}
}
else if (a == 2) {
if (IsEmpty(s)) {
Push(s, c);
}
else if (MyJudgePop(s) == '(') {
Push(s, c);
}
else if (MyJudgePop(s) == '+' || MyJudgePop(s) == '-') {
Push(s, c);
}
else if (MyJudgePop(s) == '*' || MyJudgePop(s) == '/') {
while (1) {
if (IsEmpty(s))
break;
if (MyJudgePop(s) == '+' || MyJudgePop(s) == '-')
break;
char c3 = Pop(s);
Push(s1, c3);
}
Push(s, c);
}
}
else if (a == 3) {
Push(s, c);
}
else if (a == 4) {
while (1) {
char ch = MyJudgePop(s);
if (ch == '(') {
Pop(s);
break;
}
char ch1 = Pop(s);
Push(s1, ch1);
}
}
else if (a == 5) {
while (!IsEmpty(s)) {
char c3 = Pop(s);
Push(s1, c3);
}
break;
}
}
LinkStack s2;
Create(s2);
while (!IsEmpty(s1)) {
char c = Pop(s1);
Push(s2, c);
}
Display(s2);
return 0;
}
第一次发,不标准,日后会改进代码的可读性