头文件
#ifndef _STACK_H_
#define _STACK_H_
#define SIZE 10
typedef enum {FALSE = 0 , TRUE} BOOL;
typedef int Data;
typedef struct _node
{
Data data;
struct _node *next;
}Node;
typedef struct stack
{
Node head;
}Stack;
//初始化栈
void Init(Stack *s);
//入栈
void Push(Stack *s , Data data);
//出栈
void Pop(Stack *s);
//判断空栈
BOOL Empty(Stack *s);
//判断满栈
BOOL Full(Stack *s);
//获取栈顶 元素
Data GetTop(Stack *s);
#endif // _STACK_H_
功能函数
#include "stack.h"
#include <stdlib.h>
#include <stdio.h>
//初始化栈
void Init(Stack *s)
{
if (NULL == s)
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 *node = (Node *)malloc(sizeof(Node)/sizeof(char));
if (node == NULL)
return;
node->data = data;
node->next = s->head.next;
s->head.next = node;
}
//出栈
void Pop(Stack *s)
{
if (NULL == s)
return ;
if(Empty(s) == TRUE)
return ;
Node *p = s->head.next;
s->head.next = p->next;
free (p);
}
//获取栈顶 元素
Data GetTop(Stack *s)
{
if (NULL == s)
return;
if(Empty(s) == TRUE)
{
printf("无栈顶元素\n");
exit(-1);
}
return s->head.next->data;
}
主函数
#include <stdio.h>
#include "stack.h"
#include <string.h>
BOOL jud(Stack *s , int ope) //判断操作符是否入栈
{
//if (NULL == s)
//return FALSE;
if (Empty(s)) //若为空栈,直接入栈
return TRUE;
int top = GetTop(s); //若非空栈,获取栈顶元素
switch(top) //若操作符优先级高于栈顶元素,入栈
{
case'+':
case'-':
if ('*' == ope || '/' == ope || '(' == ope)
return TRUE;
break;
case'*':
case'/':
if ('(' == ope)
return TRUE;
break;
case'(': //若栈顶为( 则都要入栈,但操作符为 )时需要释放(
if (')' == ope)
{
Pop(s);
}
return TRUE;
default:
break;
}
return FALSE;
}
//计算
void calc (Stack *s_nums , Stack *s_opes)
{
int num1 = GetTop(s_nums);
Pop(s_nums);
int num2 = GetTop(s_nums);
Pop(s_nums);
int ope = GetTop(s_opes);
Pop(s_opes);
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_nums , res); //运算结果入栈
}
//对操作符进行操作
void deal_ope(Stack *s_nums , Stack *s_opes , int ope)
{
if (jud(s_opes , ope) == TRUE)
{
Push(s_opes , ope);
}
else
{
while(jud(s_opes , ope) == FALSE)
{
calc (s_nums , s_opes);
}
if(')' != ope)
Push(s_opes , ope);
}
}
int main()
{
char buf[100];
fgets(buf , 100 , stdin);
buf[strlen(buf) - 1] = '\0';
Stack s_nums;
Stack s_opes;
Init(&s_nums);
Init(&s_opes);
char *p = buf;
while(*p)
{
if (*p >= '0' && *p <= '9')
{
int num = 0;
while(*p >= '0' && *p <= '9')
{
num = num*10 + *p - '0';
p++;
}
Push(&s_nums , num);
continue;
}
deal_ope(&s_nums , &s_opes , *p);
p++;
}
while(!Empty(&s_opes))
{
calc (&s_nums , &s_opes);
}
int res = GetTop(&s_nums);
printf("结果为 %d\n", res);
return 0 ;
}