头文件Stack.h
#ifndef _STACK_H_
#define _STACK_H_
#define SIZE 10
typedef enum {FALSE, TRUE} BOOL;
typedef int Data;
typedef struct _Node
{
Data data;
struct _Node *next;
}Node;
typedef struct _Stack
{
Node *head;
}Stack;
//初始化栈
void Init(Stack *s);
//判断空栈
BOOL Empty(Stack *s);
//压栈
void Push(Stack *s, Data data);
//出栈
void Pop(Stack *s);
//获取栈顶数据
Data GetTop(Stack *s);
#endif //_STACK_H_
Stack.c
#include "Stack.h"
#include <stdlib.h>
void Init(Stack *s)
{
if(NULL == s)
return ;
s->head = (Node *)malloc(sizeof(Node)/sizeof(char));
if(NULL == s->head)
return ;
s->head->next = NULL;
}
BOOL Empty(Stack *s)
{
if(NULL == s)
return FALSE;
if(s->head->next == NULL)
return TRUE;
return FALSE;
}
void Push(Stack *s, Data data)
{
if(NULL == s)
return ;
Node *tmp = (Node *)malloc(sizeof(Node)/sizeof(char));
tmp->data = data;
tmp->next = s->head->next;
s->head->next = tmp;
}
void Pop(Stack *s)
{
if(NULL == s)
return ;
if(Empty(s) == TRUE)
return ;
Node *tmp = s->head->next;
s->head->next = tmp->next;
free(tmp);
}
Data GetTop(Stack *s)
{
if(NULL == s)
return ;
if(Empty(s) == TRUE)
exit(-1);
return s->head->next->data;
}
main.c
#include “Stack.h”
#include <stdio.h>
//判断是否入栈
BOOL jud(Stack *s_ope, int ope)
{
//判断操作符栈是否为空
if(Empty(s_ope))
return TRUE;
int top = GetTop(s_ope);
switch(top)
{
case '+':
case '-':
if(ope == '*' || ope == '/' || ope =='(')
{
return TRUE;
}
break;
case '*':
case '/':
if(ope == '(')
{
return TRUE;
}
break;
case '(':
if(ope == ')')
{
Pop(s_ope);
}
return TRUE;
break;
default:
break;
}
return FALSE;
}
//计算
void cal(Stack *s_ope, Stack *s_num)
{
int num1 = GetTop(s_num);
Pop(s_num);
int num2 = GetTop(s_num);
Pop(s_num);
int ope = GetTop(s_ope);
Pop(s_ope);
int res;
switch(ope)
{
case '+':
res = num1+num2;
break;
case '-':
res = num2-num1;
break;
case '*':
res = num1*num2;
break;
case '/':
res = num2/num1;
break;
default:
break;
}
Push(s_num, res);
}
//处理符号
void deal_ope(Stack *s_ope, Stack *s_num, int ope)
{
//判断是否入栈
if(jud(s_ope, ope) == TRUE)
{
Push(s_ope, ope);
}
else
{
while(jud(s_ope, ope) == FALSE)
{
cal(s_ope, s_num);
}
if(ope != ')')
Push(s_ope, ope);
}
}
int main()
{
Stack s_num; //操作数栈
Stack s_ope; //操作符栈
Init(&s_num);
Init(&s_ope);
char string[100] = {0};
char *ps = string;
scanf("%s", string);
while(*ps != '\0')
{
if(*ps > '0' && *ps < '9')
{
int num = 0;
while(*ps > '0' && *ps < '9')
{
num = num*10 + *ps - '0';
ps++;
}
Push(&s_num, num);
continue;
}
deal_ope(&s_ope, &s_num, *ps); //处理符号
ps++;
}
while(!Empty(&s_ope))
{
cal(&s_ope, &s_num);
}
int result = GetTop(&s_num);
printf("result = %d\n", result);
Pop(&s_num);
return 0;
}