栈的应用——四则表达式求值

   栈的应用有很多,四则运算是一个比较常见的应用。对于四则运算,括号内的要先运算,而且还要先乘除后加减,又要涉及到负数和浮点数,看上去简简单单的式子,其实暗藏杀机。
    常用的方法是利用后缀表达式(逆波兰)进行计算。主要分为两步:
   (1)将中缀表达式转化为后缀表达式(栈用来进出运算的符号):
    从左到右遍历中缀表达式的每一个数字和符号,若是数字就输出,既成为后缀表达式的一部分,若是符号,则判断其与栈顶符号的优先级,是右括号或优先级低于栈顶符号(乘除优先加减),则栈顶元素依次出栈并输出,并将当前符号进栈,一直到最终输出后缀表达式为止。

后缀表达式的定义:http://baike.baidu.com/link?url=lrZhREhfzicvVM4lyN6wTorIDiA-3PjYX1oBxwS0qlgwKjJjjKCTZnHYZU8Eb4D020qFZ5LCYjFcqHCwtLBPCq
(2)将后缀表达式进行运算得出结果(栈用来进出运算的数字)
从左到右遍历表达式的每个数字和符号,遇到是数字就进栈,遇到是符号,就将处于栈顶两个数字出栈,进行运算,运算结果进栈,一直到最终获得结果。
下面 我贴上 用c手动模拟栈 和stl已有栈的函数 模拟这个过程~!(不支持浮点类型)
使用C语言实现的算法:(没有用到stl手动模拟栈)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define OK      1 
#define ERROR   0
#define TRUE    1
#define FALSE   0
#define MAXSIZE 50

typedef int Status;
typedef int SElemType;

//定义一个顺序存储栈
typedef struct
{
    SElemType data[MAXSIZE];
    int top;
}SqStack;

/*******************栈的基本操作********************************/
Status init_stack(SqStack *s)
{
    s->top = -1;
    return OK;
}

Status clear_stack(SqStack *s)
{
    s->top = -1;
    return OK;
}

Status stack_empty(SqStack s)
{
    if(s.top == -1)
        return TRUE;
    else
        return FALSE;
}

int stack_length(SqStack *s)
{
    return s->top+1;
}

Status push(SqStack *s, SElemType e)
{
    if(s->top == MAXSIZE-1)
        return ERROR;
    s->top++;
    s->data[s->top] = e;
    return OK;
}

Status pop(SqStack *s, SElemType *e)
{
    if(s->top == -1)
        return ERROR;
    *e = s->data[s->top];
    s->top--;
    return OK;
}

/*******************中序表达式转换为后续表达式********************************/
Status infix_to_postfix(char *infix, char *postfix)
{
    SqStack s;
    int e = 0;
    int i = 0, j = 0;
    int flag = 0;

    if(init_stack(&s) != OK)
        return ERROR;

    while(infix[i]!='\0')
    {
        while(infix[i]>='0' && infix[i]<='9')    //如果是数字则输出
        {
            if(flag)
            {
                flag = 0;
                postfix[j++] = '-';
            }
            postfix[j++] = infix[i];
            i++;
            if(infix[i]<'0' || infix[i]>'9')
                postfix[j++] = ' ';
        }
        if(infix[i]==')' || infix[i]==']' || infix[i]=='}')       //如果符号,则进行栈操作
        {
            pop(&s, &e);
            while(e!='(' && e!='[' && e!='{')
            {
                postfix[j++] = e;
                postfix[j++] = ' ';
                pop(&s, &e);
            }
        }
        else if(infix[i]=='+' || infix[i]=='-')
        {
            if(infix[i] == '-' && (i==0 || (i!=0 && (infix[i-1]<'0' || infix[i-1]>'9'))))  //当'-'号处于第一位,或前面是符号时,为负号标志
                flag = 1;     
            else if(stack_empty(s))
                push(&s, infix[i]);
            else
            {
                do
                {
                    pop(&s, &e);
                    if(e=='(' || e=='[' || e== '{')
                        push(&s, e);
                    else
                    {
                        postfix[j++] = e;
                        postfix[j++] = ' ';
                    }
                }while(!stack_empty(s) && e!='(' && e!='[' && e!='{');
                push(&s, infix[i]);
            }
        }
        else if(infix[i]=='*' || infix[i]=='/' || infix[i]=='(' || infix[i]=='[' || infix[i] == '{')
            push(&s, infix[i]);
        else if(infix[i] == '\0')
            break;
        else
            return ERROR;
        i++;
    }

    while(!stack_empty(s))
    {
        pop(&s,&e);
        postfix[j++] = e;
        postfix[j++] = ' ';
    }

    clear_stack(&s);
    return OK;
}

/*******************根据后续表达式计算结果********************************/
Status calculate(char *postfix, int *result)
{
    SqStack s;
    char *op; //存放后缀表达式中的每个因数或运算符  
    char *buf=postfix; //声明bufhe saveptr两个变量,是strtok_r函数的需要。  
    char *saveptr=NULL;
    int d,e,f;

    if(init_stack(&s) != OK)
        return ERROR;

    while((op = strtok(buf, " ")) != NULL)
    {
        buf = NULL;
        switch(op[0])
        {
            case '+':
                pop(&s, &d);
                pop(&s, &e);
                f = d+e;
                push(&s, f);
                break;
            case '-':
                if(op[1]>='0' && op[1]<='9')    //是负号而不是减号
                {
                    d = atoi(op);
                    push(&s, d);
                    break;
                }
                pop(&s, &d);
                pop(&s, &e);
                f = e-d;
                push(&s, f);
                break;
            case '*':
                pop(&s, &d);
                pop(&s, &e);
                f = e*d;
                push(&s, f);
                break;
            case '/':
                pop(&s, &d);
                pop(&s, &e);
                f = e/d;
                push(&s, f);
                break;
            default:
                d = atoi(op);
                push(&s, d);
                break;
        }
    }
    pop(&s, result);
    clear_stack(&s);
}

void main()
{
    char infix[MAXSIZE] = {0};
    char postfix[MAXSIZE] = {0};
    int result = 0;

    scanf("%s", infix);

    infix_to_postfix(infix, postfix);
    calculate(postfix, &result);

    printf("%d\n",result);
}

下面这个是用stl 栈已有的函数 模拟这个过程 ,感觉没有和上面代码量差不多。。。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<algorithm>
#define MAXSIZE 100
using namespace std;
int infix_to_postfix(char *infix,char *postfix)
{
    stack <int>s;
    int e=0,i=0,j=0,flag=0;
    if(!s.empty())
    return 0;
    while(infix[i]!='\0')
    {
        while(infix[i]>='0'&&infix[i]<='9')  //如果是数字则之间输出到后缀表达式的数组里
        {
            if(flag)
            {
                flag=0;
                postfix[j++]='-';
            }
            postfix[j++] = infix[i];
            i++;
            if(infix[i]<'0' || infix[i]>'9')//下一个字符是运算符号就空一个空格
            postfix[j++] = ' ';
        }
        if(infix[i]==')')
        {
            e=s.top();
            while(e!='(')
            {
                postfix[j++]=e;
                postfix[j++]=' ';
                s.pop();
                e=s.top();
            }
            s.pop();//确保把左括号删掉
        }
        else if(infix[i]=='+'||infix[i]=='-')
        {
           if(infix[i] == '-' && (i==0 || (i!=0 && (infix[i-1]<'0' || infix[i-1]>'9'))))  //当'-'号处于第一位,或前面是符号时,为负号标志
                flag = 1;
           else if(s.empty())
                s.push(infix[i]);
           else
           {
               do
               {
                   e=s.top();
                   s.pop();
                   if(e=='(' || e=='[' || e== '{')
                   s.push(e);
                   else
                   {
                        postfix[j++] = e;
                        postfix[j++] = ' ';
                   }
               }while(!s.empty()&&e!='('&&e!='{'&&e!='[');
               s.push(infix[i]);
           }
        }
        else if(infix[i]=='*' || infix[i]=='/' || infix[i]=='(' || infix[i]=='[' || infix[i] == '{')
                    s.push(infix[i]);
        else if(infix[i] == '\0')
            break;
        else
            return 0;
        i++;
    }
    while(!s.empty())
    {
        e=s.top();
        postfix[j++]=e;
        postfix[j++]=' ';
        s.pop();
    }
    cout<<postfix<<endl;
    return 1;
}
int calculate(char *postfix, int *result)
{
    stack <int>s;
    char *op; //存放后缀表达式中的每个因数或运算符
    char *buf=postfix; //声明bufhe saveptr两个变量,是strtok_r函数的需要。
    char *saveptr=NULL;
    int d,e,f;
    if(!s.empty())
     return 0;
     while((op = strtok(buf, " ")) != NULL)
    {
        buf = NULL;
        switch(op[0])
        {
          case '+':
                d=s.top();
                s.pop();
                e=s.top();
                s.pop();
                f = d+e;
                 s.push(f);
                break;
            case '-':
                if(op[1]>='0' && op[1]<='9')    //是负号而不是减号
                {
                    d = atoi(op);
                    s.push(d);
                    break;
                }
                d=s.top();
                s.pop();
                e=s.top();
                s.pop();
                f = e-d;
                s.push(f);
                break;
            case '*':
                d=s.top();
                s.pop();
                e=s.top();
                s.pop();
                f = e*d;
                s.push(f);
                break;
            case '/':
                d=s.top();
                s.pop();
                e=s.top();
                s.pop();
                f = e/d;
                s.push(f);
                break;
            default:
                d = atoi(op);
                s.push(d);
                break;
        }
    }
    *result=s.top();
    s.pop();

}

int main(void)
{
    while(1)
    {
    char infix[MAXSIZE] = {0};
    char postfix[MAXSIZE] = {0};
    int result = 0;
    cin>>infix;
    infix_to_postfix(infix, postfix);
    calculate(postfix, &result);
    cout<<result<<endl;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值