‘’‘
(11 + 3)× 2 -5
顺序存储栈来实现
’‘’
sqstack.h
#ifndef SQSTACK_H__
#define SQSTACK_H__
#define MAXSIZE 32
typedef int datatype
typedef struct node_st
{
datatype data[MAXSIZE];
int top;
}sqstack;
sqstack *st_create(void);
int st_isempty(sqstack *);
int st_push(sqstack *,datatype *);
int st_pop(sqstack *,datatype *);
int st_top(sqstack *,datatype *);
void st_travel(sqstack *);
void st_destory(sqstack *);
#endif
sqstack.c
#include<stdio.h>
#include<stdlib.h>
#include"sqstack.h"
sqstack *st_create(void)
{
sqstack *st;
st = malloc(sizeof(*st));
if(st == NULL)
return NULL;
st->top = -1;
return st;
}
int st_isempty(sqstack *st)
{
return (st->top == -1);
}
int st_push(sqstack *st,datatype *data)
{
if(st->top == MAXSIZE -1)
return -1;
st->data[++st->top] = *data;
return 0;
}
int st_pop(sqstack *st,datatype *data)
{
if(st_isempty(st))
return -1;
*data = st->data[st->top--];
return 0;
}
int st_top(sqstack *st,datatype *data)
{
if(st_isempty(st))
return -1;
*data = st->data[st->top];
return 0;
}
void st_travel(sqstack *st)
{
int i;
if(st_isempty(st))
return ;
for(i = 0; i < st->top;i++)
printf("%d ",st->data[i]);
printf("\n");
}
void st_destory(sqstack *st)
{
free(st);
}
main.c
#include<stdio.h>
#include<stdlib.h>
#include"sqstack.h"
void compute(sqsatck *snum,datatype *op)
{
datatype n1,n2,n;
st_pop(snum,&n2);
st_pop(snum,&n1);
switch(*op)
{
case '+':
n = n1+n2;
break;
case '-':
n = n1-n2;
break;
case '*':
n = n1*n2;
break;
case '/':
n = n1/n2;
break;
default:
exit(1);
}
st_push(snum,&n);
}
static void deal_bracket(sqstack *snum,sqstack *sop)
{
datatype old_op;
st_top(sop,&old_op);
while(old_op != '(')
{
st_pop(sop,&old_op);
compute(snum,&old_op);
st_top(sop,&old_op);
}
st_pop(sop&old_op);
}
static int get_pri(int op)
{
switch(op)
{
case '(':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
default:
return -1;
}
}
static void deal_op(sqstack *snum,sqstack *sop,int op)
{
datatype old_op;
if(st_isempty(sop) || op == '(')
{
st_push(sop,&op);
return ;
}
st_top(sop,&old_op);
if(get_pri(op) > get_pri(old_op))
{
st_push(sop,&op);
return ;
}
while(get_pri(op) <= get_pri(old_op))
{
st_pop(sop,&old_op);
computer(snum,&old_op);
if(st_isempty(sop))
break;
st_top(sop,&old_op)
}
st_push(sop,&op);
}
int main()
{
int i =0;
char str[]="(11+3)*2-5";
sqstack *snum,*sop;
int value = 0;
int flag = 0;
snum = st_create();
if(sum == NULL)
exit(1);
sop = st_create();
if(sop == NULL)
exit(1);
while(str[i] != '\0')
{
if(str[i] > '0' && str[i] < '9')
{
value = value *10 + (str[i] - '0');
flag = 1;
}else
{
if(flag)
{
st_push(snum,&value);
flag = 0;
value = 0;
}
if(str[i] == ')')
{
deal_bracket(snum,sop);
}
else
{
deal_op(snum,sop,str[i]);
}
}
i++;
}
if(flag)
st_push(snum,&value);
while(!st_isempty(sop))
{
datatype old_op;
st_pop(sop,&old_op);
computer(snum,&old_op);
}
st_travel(snum);
st_destory(snum);
st_destroy(sop);
exit(0);
}
Makefile
all:sqstack
sqstack:sqstack.o main.o
$(CC) $^ -o $@
clean:
rm sqstack *.o -rf