#include<bits/stdc++.h>
#define n 100000
typedef struct SNode* Stack;
typedef char elementtype;
struct SNode {
elementtype data;
struct SNode* next;
};
Stack createstack()
{
Stack p;
p = (Stack)malloc(sizeof(struct SNode));
p->next = NULL;
return p;
}
int IsEmpty(Stack p)
{
return (p->next == NULL);
}
void push(elementtype item, Stack p) {
struct SNode* t;
t = (Stack)malloc(sizeof(struct SNode));
t->data = item;
t->next = p->next;
p->next = t;
}
elementtype pop(Stack p)
{
struct SNode* f;
elementtype te;
if (IsEmpty(p))
{
printf("堆栈空");
return NULL;
}
else {
f = p->next;
te = f->data;
p->next = f->next;
free(f);
return te;
}
}
int main()
{
int i, l;
Stack p = createstack();
char a[n];
scanf("%s", a);
l = strlen(a);
for (i = 0; i < l; i++)
{
if (a[i] >= 'a' && a[i] <= 'z') //字母直接输出
{
printf("%c", a[i]);
}
else if (a[i] == '+' || a[i] == '-')
{
while (1)
{
if (IsEmpty(p)==1 || p->next->data == '(') //②直到栈顶为空或为'(',将'+'或'-'放入栈顶
{
push(a[i],p);
break;
}
else//①新到的'+'和'-'优先级最低,放入后会吃掉栈顶的符号并打印出来
{
printf("%c", pop(p));
}
}
}
else if (a[i] == '(') //左括号直接压入栈顶
{
push(a[i],p);
}
else if (a[i] == ')') //右括号,弹出栈顶元素,直至碰到左括号
{
for (; p->next->data != '('; p=p->next)
{
printf("%c", p->next->data);
}
pop(p);
}
else if (a[i] == '*' || a[i] == '/') //新到的'*'和'/'和栈内元素相比优先级最高,直接入栈
{
push(a[i],p);
}
}
for (; p->next!=NULL; p=p->next) //输出栈内剩余元素
{
printf("%c", p->next->data);
}
printf("\n");
return 0;
}
数据结构实验之栈与队列二:一般算术表达式转换成后缀式
最新推荐文章于 2020-05-09 17:35:53 发布