C语言使用栈结构实现后缀表达式计算器(可以实现带括号的加减乘除简单计算)
头文件
stack.h
#ifndef STACK_H
#define STACK_H
#include <stdio.h>
#include <stdlib.h>
#define SUCCESS 1000
#define FAILURE 1001
typedef struct
{
int data;
struct Node *next;
}Node;
typedef struct
{
Node *top;
int length;
}Stack;
int InitStack(Stack *stack);
int push(Stack *s, int num);
int GetTop(Stack *s);
int pop(Stack *s);
int EmptyStack(Stack *s);
#endif
stack.c
#include "stack.h"
int InitStack(Stack *s)
{
if (NULL == s)
{
return FAILURE;
}
s->top = NULL;
s->length = 0; //空栈
return SUCCESS;
}
int push(Stack *s, int num)
{
if (NULL == s)
{
return FAILURE;
}
Node *n = malloc(sizeof(Node));
if (NULL == n)
{
return FAILURE;
}
n->data = num;
n->next = s->top;
s->top = n; //更新栈顶指针
s->length++;
return SUCCESS;
}
int GetTop(Stack *s)
{
if (NULL == s)
{
return FAILURE;
}
if (s->top == NULL)
{
return FAILURE;
}
return s->top->data;
}
int pop(Stack *s)
{
if (NULL == s)
{
return FAILURE;
}
if (s->top == NULL) //空栈不能出栈
{
return FAILURE;
}
Node *n = s->top;
int data = n->data;
s->top = n->next;
free(n);
s->length--;
return data;
}
int EmptyStack(Stack *s)
{
if (NULL == s)
{
return FAILURE;
}
return (s->top == NULL) ? SUCCESS : FAILURE;
}
main.c
#include "stack.h"
int Priority(char ch)
{
switch(ch)
{
case '(':
return 3;
case '*':
return 2;
case '/':
return 2;
case '+':
return 1;
case '-':
return 1;
default:
return 0;
}
}
int main()
{
Stack s_num,s_opt; //定义数字栈、符号栈
if (InitStack(&s_num) == FAILURE || InitStack(&s_opt) == FAILURE)
{
printf("Failure1!\n");
return -1;
}
char opt[128] = {0};
int i = 0, tmp = 0, num1, num2;
printf("Please enter an expression:\n");
scanf("%s", opt);
while (opt[i] != '\0' || EmptyStack(&s_opt) != SUCCESS) //表达式不为空或栈不为空就继续
{
if (opt[i] >= '0' && opt[i] <= '9') //若下位是数字,求出asc码
{
tmp *=10;
tmp += opt[i] - '0';
i++;
if (opt[i] < '0' || opt[i] > '9') //若下位不是数字,将tmp入栈;若下位是数字继续循环
{
push(&s_num, tmp);
tmp = 0;
}
}
else //操作符
{
if (EmptyStack(&s_opt) == SUCCESS || Priority(opt[i]) > Priority(GetTop(&s_opt)) ||
(GetTop(&s_opt) == '(') && (opt[i] != ')'))
{
push(&s_opt, opt[i]);
i++;
//continue;
}
else if(GetTop(&s_opt) == '(' && opt[i] == ')'){
pop(&s_opt);
i++;
//continue;
}
else{
if (Priority(opt[i]) <= Priority(GetTop(&s_opt)) || ((opt[i] == ')') && GetTop(&s_opt) != ')') ||
opt[i] == '\0' && EmptyStack(&s_opt) != SUCCESS)
{
switch(pop(&s_opt))
{
case '+':
num1 = pop(&s_num);
num2 = pop(&s_num);
push(&s_num, num1 + num2);
break;
case '-':
num1 = pop(&s_num);
num2 = pop(&s_num);
push(&s_num, num2 - num1);
break;
case '*':
num1 = pop(&s_num);
num2 = pop(&s_num);
push(&s_num, num1 * num2);
break;
case '/':
num1 = pop(&s_num);
num2 = pop(&s_num);
push(&s_num, num2 / num1);
break;
}
}
}
}
}
printf("The result is:%d\n", GetTop(&s_num));
return 0;
}