这是小米手机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=