逆波兰表达式栈实现c++
时间: 2023-04-07 10:03:11 浏览: 87
我可以回答这个问题。逆波兰表达式是一种后缀表达式,可以通过栈来实现。具体实现方法是,遍历表达式中的每个元素,如果是数字,则将其压入栈中;如果是运算符,则从栈中弹出两个数字进行运算,并将结果压入栈中。最终,栈中只剩下一个元素,即为表达式的计算结果。在C语言中,可以使用数组来模拟栈的实现。
相关问题
c++栈实现逆波兰表达式代码
以下是C语言栈实现逆波兰表达式的代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXOP 100
#define NUMBER '0'
int getop(char []);
void push(double);
double pop(void);
int main()
{
int type;
double op2;
char s[MAXOP];
while ((type = getop(s)) != EOF) {
switch (type) {
case NUMBER:
push(atof(s));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
if (op2 != 0.0)
push(pop() / op2);
else
printf("error: zero divisor\n");
break;
case '\n':
printf("\t%.8g\n", pop());
break;
default:
printf("error: unknown command %s\n", s);
break;
}
}
return 0;
}
#define MAXVAL 100
int sp = 0;
double val[MAXVAL];
void push(double f)
{
if (sp < MAXVAL)
val[sp++] = f;
else
printf("error: stack full, can't push %g\n", f);
}
double pop(void)
{
if (sp > 0)
return val[--sp];
else {
printf("error: stack empty\n");
return 0.0;
}
}
int getch(void);
void ungetch(int);
int getop(char s[])
{
int i, c;
while ((s[0] = c = getch()) == ' ' || c == '\t')
;
s[1] = '\0';
if (!isdigit(c) && c != '.')
return c;
i = 0;
if (isdigit(c))
while (isdigit(s[++i] = c = getch()))
;
if (c == '.')
while (isdigit(s[++i] = c = getch()))
;
s[i] = '\0';
if (c != EOF)
ungetch(c);
return NUMBER;
}
#define BUFSIZE 100
char buf[BUFSIZE];
int bufp = 0;
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c)
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
用栈实现逆波兰表达式C++代码
以下是用栈实现逆波兰表达式的C代码:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_STACK_SIZE 100
typedef struct {
int top;
int data[MAX_STACK_SIZE];
} Stack;
void push(Stack *s, int value) {
if (s->top == MAX_STACK_SIZE - 1) {
printf("Stack overflow\n");
exit(1);
}
s->data[++s->top] = value;
}
int pop(Stack *s) {
if (s->top == -1) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top--];
}
int main() {
Stack s;
s.top = -1;
char c;
int num1, num2;
while ((c = getchar()) != '\n') {
if (isdigit(c)) {
push(&s, c - '0');
} else {
num2 = pop(&s);
num1 = pop(&s);
switch (c) {
case '+':
push(&s, num1 + num2);
break;
case '-':
push(&s, num1 - num2);
break;
case '*':
push(&s, num1 * num2);
break;
case '/':
push(&s, num1 / num2);
break;
default:
printf("Invalid operator\n");
exit(1);
}
}
}
printf("%d\n", pop(&s));
return 0;
}