数据结构练习——栈(逆波兰算法)

知识补充:from wiki

逆波兰表示法Reverse Polish notationRPN,或逆波兰记法),是一种是由波兰数学家扬·武卡谢维奇1920年引入的数学表达式方式,在逆波兰记法中,所有操作符置于操作数的后面,因此也被称为后缀表示法。逆波兰记法不需要括号来标识操作符的优先级。

https://zh.wikipedia.org/wiki/%E9%80%86%E6%B3%A2%E5%85%B0%E8%A1%A8%E7%A4%BA%E6%B3%95

代码实现c语言

栈实现逆波兰运算

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
// 初始化栈的大小
#define STACK_INIT_SIZE 20
// 追加栈空间时,栈的增量
#define STACKINCREMENT  10

typedef double ElemType;
typedef struct
{
    ElemType *base;
    ElemType *top;
    int stackSize;
} Stack;

InitStack(Stack *s)
{
    s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
    if( !s->base )
        exit(0);

    s->top = s->base;   //初始化的时候首尾指向相同位置
    s->stackSize = STACK_INIT_SIZE;
}

Push(Stack *s, ElemType e)
{
    // 栈满,追加空间
    if( s->top - s->base >= s->stackSize )
    {
        s->base = (ElemType *)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
        if( !s->base )
            exit(0);

        s->top = s->base + s->stackSize;
        s->stackSize = s->stackSize + STACKINCREMENT;
    }

    *(s->top) = e;      // 存放数据
    s->top++;
}

Pop(Stack *s, ElemType *e)
{
    if( s->top == s->base )
        return;

    *e = *--(s->top);   // 将栈顶元素弹出并修改栈顶指针
}

int StackLen(Stack *s)
{
    return (s->top - s->base);
}

void RPN()
{
    Stack s;
    char c;
    double d, e;
    char str[100];
    int i = 0;

    InitStack( &s );

    printf("请按逆波兰表达式输入待计算数据,数据与运算符之间用空格隔开,以#作为结束标志: \n");
    //以读取逐个字符的方式,计算
    scanf("%c", &c);

    while( c != '#' )
    {
        while( isdigit(c) || c=='.' )  // 用于过滤数字
        {
            str[i++] = c;
            str[i] = '\0';
            if( i >= 10 )
            {
                printf("出错:输入的单个数据过大!\n");
                return -1;
            }
            else
            {
                scanf("%c", &c);
                if( c == ' ' )
                {
                    d = atof(str);
                    Push(&s, d);
                    i = 0;
                    break;
                }
            }
        }
    //当输入运算符时
        switch( c )
        {
        case '+':
            Pop(&s, &e);
            Pop(&s, &d);
            Push(&s, d+e);
            break;
        case '-':
            Pop(&s, &e);
            Pop(&s, &d);
            Push(&s, d-e);
            break;
        case '*':
            Pop(&s, &e);
            Pop(&s, &d);
            Push(&s, d*e);
            break;
        case '/':
            Pop(&s, &e);
            Pop(&s, &d);
            if( e != 0 )
            {
                Push(&s, d/e);
            }
            else
            {
                printf("\n出错:除数为零!\n");
                return -1;
            }
            break;
        }

        scanf("%c", &c);
    }

    Pop(&s, &d);
    printf("\n最终的计算结果为:%f\n", d);

    return d;
}

void main()
{
    while(1)
    RPN();
}

// (1-2)+(5*6)=-29
// 转换为 输入:1 2 - 5 6 * +

 

猜你喜欢

转载自blog.csdn.net/qq_41420747/article/details/81840311
今日推荐