算法杂谈--四则运算

这是小米手机2014校园招聘时候的算法题,它只要求10以内的四则运算!我当时用堆栈实现,可惜没考虑有括号的情形。此例子是包含括号的四则运算,支持负数的直接加减乘除,并且运算结果为分数(前几天写的比较急,没考虑除数为0的情形测试的也不是很多,能运行,但应该会有一些小问题)


无括号的四则运算,用堆栈即可实现!有括号的四则运算,通过从内到外去括号进行递归即可得到解。在去括号过程后得到的解用1#2的形式表示分数(1#2表示二分之一)。


例如(-1--3*2)/-6+-2*-8*(2*-1+2*(-1--4))的递归过程如下

5#1/-6+-2*-8*(2*-1+2*(-1--4))

5#1/-6+-2*-8*(2*-1+2*3#1)

5#1/-6+-2*-8*4#1

379/6(此即为所求)

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

//分数结构,fz表示分子,fm表示分母
typedef struct frac
{
	int fz;
	int fm;
}frac;

//链栈节点定义
typedef struct node
{
	frac fa;
	struct node *next;
}node;

//链栈定义,bottom为底,top为顶
typedef struct
{
	node *bottom;
	node *top;
}heap;

//初始化堆栈
void init(heap *h)
{
	assert(h!=NULL);
	h->bottom=h->top=NULL;
}

//往堆栈h中压入分数c
void push(heap *h,frac *c)
{
	assert(h!=NULL);
	node *n=(node*)malloc(sizeof(node));
	n->fa=*c;
	n->next=NULL;
	if(h->bottom==NULL&&h->top==NULL)
	{
		h->bottom=h->top=n;
	}
	else
	{
		h->top->next=n;
		h->top=n;
	}
}

//从堆栈h中取出一个分数
frac pop(heap *h)
{
	assert(h!=NULL);
	if(h->bottom==NULL&&h->bottom==NULL)
	{
		printf("pop error!\n");
		exit(-1);
	}
	frac res;
	res=h->top->fa;
	if(h->bottom==h->top&&h->bottom!=NULL)
	{
		free(h->bottom);
		h->top=h->bottom=NULL;
		return res;
	}

	node *p=h->bottom;
	while(p->next!=h->top)p=p->next;
	free(h->top);
	h->top=
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值