简单计算器

/*
题意:计算表达式,计算该表达式的值。
思路:遇到'+'、'-'就入栈,遇到'*'、'/'就直接运算,最后再计算栈中元素的和。
*/
//Accepted Code:
#include <bits/stdc++.h>
using namespace std;
typedef double ElemType;
typedef struct ListPtr {
    ElemType data;
    ListPtr *prior;
}*lists;
int len;
lists head, tail;
void Alloc(lists &p) {
    p = (ListPtr *)malloc(sizeof(ListPtr));
    p -> prior = NULL;
}
void link() {
    len = 0;
    Alloc(head);
    tail = head;
}
void push(ElemType e) {
    lists p;
    Alloc(p);
    p -> data = e;
    p -> prior = tail;
    tail = p;
    len++;
}
void pop() {
    len--;
    lists p = tail;
    tail = tail -> prior;
    free(p);
}
ElemType top() {
    return tail -> data;
}
int main() {
    char ch, opt;
    ElemType a, b, ans;
    while (scanf("%lf%c", &a, &ch)) {
        if (!a && ch == '\n')//结束条件
            break;
        link();
        push(a);
        while (scanf("%c%lf", &opt, &b)) {
            if (opt == '+')
                push(b);
            else if (opt == '-')
                push(-b);//看成+(-b)
            else if (opt == '*') {
                b = top() * b;
                pop();
                push(b);
            }
            else if (opt == '/') {
                b = top() / b;
                pop();
                push(b);
            }
            ch = getchar();
            if (ch == '\n')
                break;
        }
        ans = 0;
        while (len) {
            ans += top();
            pop();
        }
        printf("%.2lf\n", ans);
    }
    return 0;
}

 

上一篇:静态链表过程演示及代码实现(A - B) U (B - A)


下一篇:顺序表中基本操作的实现