规则
实现
首先需要调用栈的基本函数
数据结构基础——栈
#include "stack.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
static bool Full(Stack* st)
{
return st->top == st->size;
}
static bool AppendSpace(Stack* st)
{
ElemType* new_space = (ElemType*)malloc(sizeof(ElemType) * st->size * 2);
if (new_space == NULL) return false;
for (int i = 0; i < st->size; ++i)
{
new_space[i] = st->stack_low[i];
}
free(st->stack_low);
st->stack_low = new_space;
st->size *= 2;
return true;
}
void InitStack(Stack* st, int init_size)
{
if (st == NULL) exit(0);
init_size = init_size > 0 ? init_size : 10;
st->stack_low = (ElemType*)malloc(sizeof(ElemType) * init_size);
if (st->stack_low == NULL) exit(0);
st->top = 0;
st->size = init_size;
}
bool Empty(Stack* st)
{
if (st == NULL) exit(0);
return st->top == 0;
}
bool Push(Stack* st, ElemType value)
{
if (st == NULL) exit(0);
if (Full(st))
{
if (!AppendSpace(st))
{
return false;
}
}
st->stack_low[st->top++] = value;
return true;
}
bool Pop(Stack* st)
{
if (st == NULL) exit(0);
if (Empty(st)) return false;
st->top--;
return true;
}
bool Top(Stack* st, ElemType* reval)
{
if (st == NULL) exit(0);
if (Empty(st)) return false;
*reval = st->stack_low[st->top - 1];
return true;
}
void DestroyStack(Stack* st)
{
if (st == NULL) exit(0);
free(st->stack_low);
st->stack_low = NULL;
st->top = st->size = 0;
}
static void ClearStack(Stack* st)
{
while (!Empty(st))
{
ElemType value;
Top(st, &value);
printf("%c ", value);
Pop(st);
}
}
static void DealRightPare(Stack* st)
{
while (!Empty(st))
{
ElemType value;
Top(st, &value);
Pop(st);
if (value == '(' ) break;
printf("%c", value);
}
}
static void DealPlus(Stack* st,ElemType plus)
{
while (!Empty(st))
{
ElemType value;
Top(st, &value);
Pop(st);
if (value == '(' || Empty(st)) break;
printf("%c", value);
}
Push(st, plus);//当前符号入栈
}
static void DealMul(Stack* st,ElemType mul)
{
while (!Empty(st))
{
ElemType value;
Top(st, &value);
Pop(st);
if (value == '(' || value == '+' || value == '-' || ElemType(st)) break;
printf("%c", value);
}
Push(st, mul);//当前符号入栈
}
//中缀转后缀
void InfixToSuffix(char* infix_str)
{
if (infix_str == NULL) return;
Stack st;
InitStack(&st, 10);
//遍历 infix_str 字符串
int index = 0;
while (infix_str[index] != '/0')
{
if (infix_str[index] == ' ')
{
}
if (isdigit(infix_str[index])) //判断是数字
{
printf("%c", infix_str[index]);
}
else if (infix_str[index]== '(')
{
Push(&st, infix_str[index]);
}
else if (infix_str[index] == ')')
{
DealRightPare(&st);
}
else if (infix_str[index] == '+' || infix_str[index] == '-')
{
DealPlus(&st,infix_str[index]);
}
else if (infix_str[index] == '*' || infix_str[index] == '/')
{
DealMul(&st,infix_str[index]);
}
else
{
printf("Infix String Is Error\n");
}
index++;
}
ClearStack(&st);//清空栈
}
int main()
{
char st = { 2 + 9 / 3 - 5 };
InfixToSuffix(&st);
}