SDUT-2133_数据结构实验之栈与队列三:后缀式求值

数据结构实验之栈与队列三:后缀式求值

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。

Input

输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。

Output

求该后缀式所对应的算术表达式的值,并输出之。

Sample Input

59*684/-3*+#

Sample Output

57

Hint

基本操作数都是一位正整数!

简单的后缀表达式求值,也告诉了我们为什么会转化成后缀,严格按照从左往右进行就可以了。

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

typedef struct node
{
    int data;
    struct node *next;
}Node;

typedef struct stack
{
    Node *base,*top;
}Stack;

Node *newnode()
{
    Node *t;
    t = (Node *)malloc(sizeof(Node));
    t->next = NULL;
    return t;
};

Stack *Newstack()
{
    Stack *t;
    t = (Stack *)malloc(sizeof(Stack));
    t->top = newnode();
    t->base = t->top;
    return t;
}

void push(Stack *t,int x)
{
    Node *p = newnode();
    p->data = x;
    p->next = t->top->next;
    t->top->next = p;
    t->base = p;
}

int top(Stack *t)
{
    return t->top->next->data;
}

void pop(Stack *t)
{
    Node *p;
    p = t->top->next;
    t->top->next = t->top->next->next;
    free(p);
}

int empty(Stack *t)
{
    if(t->top->next==NULL)
        return 1;
    return 0;
}

int main()
{
    Stack *t;
    char s[100050];
    int i;
    scanf("%s",s);
    t = Newstack();
    for(i=0;s[i]!='#';i++)
    {
        if(s[i]>='0'&&s[i]<='9')
            push(t,s[i] - '0');
        else
        {
            int a,b;
            a = top(t);
            pop(t);
            b = top(t);
            pop(t);
            if(s[i]=='+')
                push(t,a+b);
            else if(s[i]=='-')
                push(t,b-a);
            else if(s[i]=='*')
                push(t,a*b);
            else if(s[i]=='/')
                push(t,b/a);
        }
    }
    printf("%d
",top(t));
    return 0;
}

线性表

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

typedef struct Stack
{
    int *top,*base;
}Stack;

Stack newStack()
{
    Stack t;
    t.top = (int *)malloc(100050*sizeof(int));
    t.base = t.top;
    return t;
}

void push(Stack *t,int x)
{
    *(t->top++) = x;
}

int top(Stack t)
{
    return *(t.top-1);
}

void pop(Stack *t)
{
    t->top--;
}

int Empty(Stack t)
{
    if(t.top==t.base)
        return 1;
    return 0;
}

int main()
{
    char s[100050];
    int i,a,b;
    Stack t;
    t = newStack();
    scanf("%s",s);
    for(i=0;s[i]!='#';i++)
    {
        if(s[i]>='0'&&s[i]<='9')
            push(&t,s[i] - '0');
        else
        {
            a = top(t);
            pop(&t);
            b = top(t);
            pop(&t);
            if(s[i]=='+')
                push(&t,a+b);
            else if(s[i]=='*')
                push(&t,a*b);
            else if(s[i]=='-')
                push(&t,b-a);
            else if(s[i]=='/')
                push(&t,b/a);
        }
    }
    printf("%d
",top(t));
    return 0;
}
原文地址:https://www.cnblogs.com/luoxiaoyi/p/9747959.html