栈的应用之逆波兰表达式求值

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)//假如第一个字符为DATA则往栈中压入数据
    {
        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;
}

猜你喜欢

转载自blog.csdn.net/dream8834/article/details/82230400