堆栈学习中,四则运算不带括号版

代码如下

#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
typedef int elementtype;
struct listnode{
	elementtype num;
	char operat[8];
	struct listnode* next;
};
typedef struct listnode mystack;

mystack* create(){
	mystack* top=NULL;
	top=(mystack*)malloc(sizeof(struct listnode));
	top->next=NULL;
	return top;
}

mystack* pushnumber(mystack* top,elementtype number){
	mystack* cell=NULL;
	cell=(mystack*)malloc(sizeof(struct listnode));
	cell->num=number;
	cell->next=top->next;
	top->next=cell;
	return top;
}

mystack* pushoperat(mystack* top,char operat){
	mystack* cell=NULL;
	cell=(mystack*)malloc(sizeof(struct listnode));
	cell->operat[0]=operat;
	cell->next=top->next;
	top->next=cell;
	return top;
}

mystack* pop(mystack* top){
	mystack* tem=top;
	tem=top->next;
	top->next=tem->next;
	free(tem);
	return top;
}

int test(char operat){
	if(operat=='*'||operat=='/'){
		return 1;
	}else if(operat=='+'||operat=='-'){
		return 0;
	}
}
int calu(mystack* top){
	mystack* tem=top->next;
	int a=tem->num;
	tem=tem->next;
	if(tem->operat[0]=='*'){
		tem=tem->next;
		int b=tem->num;
		return b*a;
	}else if(tem->operat[0]=='/'){
		tem=tem->next;
		int b=tem->num;
		return b/a;
	}
}
mystack* lianxu(mystack* top){
	int a=3;
	while(a>0){
		top=pop(top);
		a--;
	}
	return top;
}

mystack* left(mystack* top,int *store){
	mystack* tem=top->next;
	while(tem!=NULL){
		int a=tem->num;
		tem=tem->next;
		if(tem==NULL){
			*store=a;
			return top;
		}
		if(tem->operat[0]=='+'){
			*store=a;
			store++;
			tem=tem->next;
		}else if(tem->operat[0]=='-'){
			*store=-a;
		    store++;
			tem=tem->next;
		}
	}
	return top;
}

void qingko(mystack* top){
    while(top->next!=NULL){
		top=pop(top);
	}
	free(top);
} 
int main(){
	mystack* top=NULL;
	top=create();
	elementtype number[50]={0};
	char operat[200]={"\0"};
	int i=0;
	int j=0;
	do{
		scanf("%d",&number[j]);
		scanf("%c",&operat[i]);
		i++;
		j++;		
	}while(operat[i-1]!='=');
	int position=i;
	int judge=0;
	int count=0;
	for(i=0;i<position+1;i++){
		top=pushnumber(top,number[i]);
		top=pushoperat(top,operat[i]);
		judge=test(operat[i]);
		if(judge==1){
			i=i+1;
			top=pushnumber(top,number[i]);
			number[i]=calu(top);
			top=lianxu(top);
			i--;
		}
	}
	int plus[50]={0};
	int *store=&plus[0];
	top=left(top,store);
	int count1=0;
	for(i=0;i<50;i++){
		count1=count1+plus[i];
	}
	qingko(top);
	printf("%d",count1);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值