Reversed Polish Notation.h
#ifndef __ReversedPolishNotation_H__
#define __ReversedPolishNotation_H__
#define MAXSIZE 10
typedef int DataType;
typedef struct StackNode
{
DataType arr[MAXSIZE];
int top;
}Stack, *pStack;
enum
{
ADD,
SUB,
MUL,
DIV,
DATA
};
typedef struct RPN
{
int opera;
int data;
}RPN;
int EmptyStack(pStack ps);
void InitStack(pStack ps);
void PushStack(pStack ps, DataType data);
DataType PopStack(pStack ps);
DataType TopStack(pStack ps);
int _RPN(RPN* p,int size);
#endif //__Reversed Polish Notation_H__
Reversed Polish Notation.c
#include "Reversed Polish Notation.h"
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
void InitStack(Stack* ps)
{
assert(ps);
ps->top = 0;
}
void PushStack(pStack ps, DataType data)
{
assert(ps);
ps->arr[ps->top++] = data;
}
int EmptyStack(pStack ps)
{
assert(ps);
return 0 == ps->top;
}
DataType PopStack(pStack ps )
{
DataType e;
assert(ps);
if (EmptyStack(ps))
{
return 0;
}
else
{
ps->top--;
e = ps->arr[ps->top];
return e;
}
}
DataType TopStack(pStack ps)
{
assert(ps);
if (EmptyStack(ps))
{
printf("栈为空!!!\n");
return 0;
}
return ps->arr[ps->top - 1];
}
int _RPN(RPN* p,int size)
{
int left;
int right;
Stack S;
InitStack(&S);
while(size--)
{
if(DATA == p->opera)
{
PushStack(&S,p->data);
}
else
{
right = TopStack(&S);
PopStack(&S);
left = TopStack(&S);
PopStack(&S);
switch(p->opera)
{
case ADD:
PushStack(&S,left + right);
break;
case SUB:
PushStack(&S,left - right);
break;
case MUL:
PushStack(&S,left * right);
break;
case DIV:
PushStack(&S,left / right);
break;
default:
break;
}
}
p++;
}
return TopStack(&S);
}
test.c
#include "Reversed Polish Notation.h"
#include <stdio.h>
#include <string.h>
void test()
{
RPN p[] = {{DATA,12},{DATA,3},{DATA,4},{ADD,0},
{MUL,0},{DATA,6},{SUB,0},{DATA,8},
{DATA,2},{DIV,0},{ADD,0}};
int size = sizeof(p)/sizeof(p[0]);
int result = _RPN(p,size);
printf("%d\n", result);
}
int main()
{
test();
return 0;
}