awawlove @ 2024-04-18 21:27:06
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct stack
{
int data;
struct stack* next;
};
void initstack(struct stack** L)
{
*L = (struct stack*)malloc(sizeof(struct stack));
(*L)->next = NULL;
}
void push(struct stack** L, int e)
{
struct stack* s = (struct stack*)malloc(sizeof(struct stack));
s->data = e;
s->next = *L;
*L = s;
}
int top(struct stack** L)
{
struct stack* p, * s;
s = *L;
p = *L;
int e;
e = (*L)->data;
p = (*L)->next;
*L = p;
s->next = NULL;
free(s);
return e;
}
int main()
{
char *a;
a = (char*)malloc(50*sizeof(char));
struct stack* L;
initstack(&L);
int num = 0, count = 0;
scanf("%s", a);
int len_a, n, m;
n = 0;
m = 0;
len_a = strlen(a);
for (int i = 0; i < len_a; i++)
{
switch (a[i])
{
case '.':
push(&L, num);
num = 0;
break;
case '+':
count = top(&L) + top(&L);
push(&L, count);
break;
case '-':
count = (-1) * (top(&L) - top(&L));
push(&L, count);
break;
case '*':
count = top(&L) * top(&L);
push(&L, count);
break;
case '/':
n = top(&L);
m = top(&L);
count = m / n;
push(&L, count);
break;
case '@':
break;
default:
num = num * 10 + (a[i] - '0');
}
n = 0;
m = 0;
count = 0;
}
free(a);
printf("%d", top(&L));
}
by luogu_tanbozhi @ 2024-06-08 12:55:06
here
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
int performOperation(char operation, int operand1, int operand2) {
switch(operation) {
case '+': return operand1 + operand2;
case '-': return operand1 - operand2;
case '*': return operand1 * operand2;
case '/': return operand1 / operand2;
default: return 0;
}
}
int evaluatePostfix(const string& expression) {
stack<int> operandStack;
string operandStr;
for (char c : expression) {
if (c == '@') {
break;
} else if (c == '.') {
int operand = stoi(operandStr);
operandStack.push(operand);
operandStr = "";
} else if (isdigit(c) || c == '.') {
operandStr += c;
} else if (isOperator(c)) {
int operand2 = operandStack.top();
operandStack.pop();
int operand1 = operandStack.top();
operandStack.pop();
int result = performOperation(c, operand1, operand2);
operandStack.push(result);
}
}
return operandStack.top();
}
int main() {
string postfixExpression;
getline(cin, postfixExpression);
int result = evaluatePostfix(postfixExpression);
cout << result << endl;
return 0;
}
@awawlove