中缀表达式转为后缀表达式规则:
从左到右遍历中缀表达式的每个数字和符号,若是数字就输出,即成为后缀表达式的一部分;若是符号,则判断其与栈顶符号的优先级,
是右括号或是优先级不高于栈顶符号(乘除优先加减),则栈顶元素一次出栈并输出,并将当前符号进栈,一直到最终输出后缀表达式为止。
*/
test.hpp
#ifndef TEST_H_
#define TEST_H_
#include"malloc.h"
#define MAXSIZE 100
typedef char SElemType;
typedef struct
{
SElemType data[MAXSIZE];
int top;
}SqStack;
//InitStack(*S):初始化操作,建立一个空栈S
SqStack * initStack();
//DestroyStack(*S):若栈存在,则销毁他
void destroyStack(SqStack * S);
//ClearStack(*S):将栈清空
void clearStack(SqStack * S);
//StackEmpty(S):若栈为空,返回true。否则返回false
bool stackEmpty(const SqStack * S);
//StackLength(S):返回栈S的元素个数
int stackLength(const SqStack S);
//GetTop(S,*e);若栈存在且非空,用e返回S的栈顶元素
void getTop(const SqStack S, SElemType * e);
//Push(*S,e):若栈S存在,插入新元素e到栈S中并成为栈顶元素
void push(SqStack * S, const SElemType e);
//Pop(*S,*e):删除栈S存在中栈顶的元素,并用e返回其值
void pop(SqStack * S, SElemType & e);
#endif // !TEST_H_
#pragma once
test.cpp
#include"test.h"
//InitStack(*S):初始化操作,建立一个空栈S
SqStack * initStack() {
SqStack *S = (SqStack *)malloc(sizeof(SqStack));
S->top = 0;
return S;
}
//DestroyStack(*S):若栈存在,则销毁他
void destroyStack(SqStack * S) {
if (S->top > 0)
free(S);
}
//ClearStack(*S):将栈清空
void clearStack(SqStack * S) {
if (S->top > 0)
{
for (size_t i = S->top; i >= 0; i--)
{
S->data[i] = 0;
}
S->top = 0;
}
}
//StackEmpty(S):若栈为空,返回true。否则返回false
bool stackEmpty(const SqStack * S) {
if (S->top > 0)
return false;
else
return true;
}
//StackLength(S):返回栈S的元素个数
int stackLength(const SqStack S) {
return S.top;
}
//GetTop(S,*e);若栈存在且非空,用e返回S的栈顶元素
void getTop(const SqStack S, SElemType * e) {
if (S.top > 0)
*e = S.data[S.top];
}
//Push(*S,e):若栈S存在,插入新元素e到栈S中并成为栈顶元素
void push(SqStack * S, const SElemType e) {
if (S->top < MAXSIZE)
{
S->data[S->top] = e;
++S->top;
}
}
//Pop(*S,*e):删除栈S存在中栈顶的元素,并用e返回其值
void pop(SqStack * S, SElemType & e) {
e = S->data[--S->top];
}
main.cpp
/*
中缀表达式转为后缀表达式规则:
从左到右遍历中缀表达式的每个数字和符号,若是数字就输出,即成为后缀表达式的一部分;若是符号,则判断其与栈顶符号的优先级,
是右括号或是优先级不高于栈顶符号(乘除优先加减),则栈顶元素一次出栈并输出,并将当前符号进栈,一直到最终输出后缀表达式为止。
*/
#include<iostream>
#include<cstdio>
#include"test.h"
int main()
{
SqStack * S = initStack();
printf("请输出表达式,以#号结束\n");
char s;
scanf("%c", &s);
while (s != '#')
{
while (isdigit(s))
{
printf("%c", s);
scanf("%c", &s);
if (!isdigit(s))
printf(" ");
}
if (s == ')')
{
char temp;
pop(S, temp);
while (temp != '(')
{
printf("%c ", temp);
pop(S, temp);
}
}
else if (s == '+' || s == '-')
{
if (stackEmpty(S))
push(S, s);
else
{
char temp;
do
{
pop(S, temp);
if (temp == '(')
push(S, temp);
else
printf("%c ", temp);
} while (!stackEmpty(S) && temp != '(');
push(S, s);
}
}
else if (s == '*' || s == '/' || s == '(')
push(S, s);
else if (s == '#')
break;
scanf("%c", &s);
}
while (stackLength(*S))
{
char temp;
pop(S, temp);
printf("%c ", temp);
}
return 0;
}