데이터 구조 에서 스 택 으로 표현 식 계산 을 실현 합 니 다.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define STACK_SIZE 64

typedef int datatype;
typedef struct _seq_stack_ {
	datatype data[STACK_SIZE];
	int top;
	int size;
}seqstack;

seqstack *creat_stack(void)
{
	seqstack *p = (seqstack *)malloc(sizeof(seqstack));
	memset(p,0,sizeof(seqstack));
	p->top = -1;
	p->size = STACK_SIZE;
	return p;
}

void annul_stack(seqstack *stack)
{
	if(stack == NULL)
		return ;
	free(stack);
}

int full_stack(seqstack *stack)
{
	if(NULL == stack)
		return -1;
	return (stack->top >= stack->size - 1);
}

int empty_stack(seqstack *stack)
{
	if(NULL == stack)
		return -1;
	return (stack->top < 0);
}

int  push_stack(seqstack *stack, datatype value)
{
	if(NULL == stack)
		return -1;
	if(full_stack(stack))
		return 1;
	stack->data[++ stack->top] = value;
	return 0;
}

datatype pop_stack(seqstack *stack)
{
	if(NULL == stack)
		return 0;
	if(empty_stack(stack))
		return 0;
	return stack->data[stack->top --];
}

datatype get_top(seqstack *stack)
{
	if(NULL == stack)
		return 0;
	return stack->data[stack->top];
}

int priority(char opt)
{
	switch(opt)
	{
	case '+':
	case '-':
		return 1;
	case '*':
	case '/':
		return 2;
	default:
		return 0;
	}
}

datatype comput_data(datatype opd1,datatype opd2,char opt)
{
	switch(opt)
	{
	case '+':
		return opd1 + opd2;
	case '-':
		return opd1 - opd2;
	case '*':
		return opd1 * opd2;
	case '/':
		return opd1 / opd2;
	default:
		return 0;
	}
}

void proc_data(seqstack *operand, seqstack*operator, char opt)
{
	datatype opd1,opd2,result;
	while(!empty_stack(operator) && priority(opt) <= priority(get_top(operator)))
	{
		opd2 = pop_stack(operand);	
		opd1 = pop_stack(operand);	
		result = comput_data(opd1,opd2,pop_stack(operator));
	printf("the result is : %d
",result); push_stack(operand,result); } push_stack(operator,opt); } int main() { char expr[STACK_SIZE] = {0}; datatype result = 0, sum = 0; datatype opd1 = 0, opd2 = 0; char *p = expr; seqstack *operand = creat_stack(); seqstack *operator = creat_stack(); gets(expr); puts(expr); while(*p != '\0') { if(*p >= '0' && *p <= '9') { sum = 0; while(*p >= '0' && *p <= '9') sum = sum * 10 + *p ++ - '0'; push_stack(operand,sum); } else proc_data(operand,operator,*p ++); } puts("-----------------------"); while(!empty_stack(operator)) { opd2 = pop_stack(operand); opd1 = pop_stack(operand); result = comput_data(opd1,opd2,pop_stack(operator)); push_stack(operand,result); } printf("the result is : %d
",get_top(operand)); return 0; }

좋은 웹페이지 즐겨찾기