链表解决亿元多项式,求解有关问题

链表解决亿元多项式,求解问题,请求帮助
#include<stdio.h>

typedef struct
{
int a;
int m;
struct *next;
}ad;

ad *init();
ad* add(ad*,ad*);
void print(ad*);

void main()
{
ad* p;//定义两个链表
ad* q;
ad* sum;
printf("初始化第一个链表\n");
p=init();
printf("初始化第二个链表\n");
q=init();
sum=add(p,q);
print(sum);
}

ad* init()
{
ad* head;
ad *p,*q;
int i=1,n=0;

head=(ad*)malloc(sizeof(ad));
head->next=NULL;
p=head;

printf("输入多项式的项数:\n");
scanf("%d",&n);

while(i<=n)
{
p=head;

while(p->next!=NULL)
{
p=p->next;
}

q=(ad*)malloc(sizeof(ad));
printf("输入系数和次幂\n");
scanf("%d%d",&q->a,&q->m);

q->next=p->next;
p->next=q;

i++;

}
return head;
}

void print(ad* head)
{
ad* p=head;
while(p->next!=NULL)
{
p=p->next;
printf("(%d %d)",p->a,p->m);

}
printf("\n");
}

ad* add(ad* a,ad* b)
{
ad* c,*q,*w,*e,*p;
c=(ad*)malloc(sizeof(ad));//初始化重构链表
c->next=NULL;

q=c;//设置零时指针

w=a->next;
e=b->next;

while(w && e)
{
// p=(ad*)malloc(sizeof(ad));
if((w->m)>(e->m))
{
p=(ad*)malloc(sizeof(ad));
p->a=e->a;
p->m=e->m;
p->next=NULL;
//p->next=q->next;
q->next=p;
q=q->next;
e=e->next;
}

if((w->m) < (e->m))
{
p=(ad*)malloc(sizeof(ad));
p->a=w->a;
p->m=w->m;
p->next=NULL;
// p->next=q->next;
q->next=p;
q=q->next;
w=w->next;

}

if((w->m)==(e->m))
{



if(((w->a)+(e->a))!=0)
{
p=(ad*)malloc(sizeof(ad));
p->m=w->m;
p->a=w->a+e->a;
p->next=NULL;
// p->next=q->next;
q->next=p;
q=q->next;
}

w=w->next;
e=e->next;

}



}
print(c);
// q->next=NULL;

if(e)//当其中一个为空时
{

q->next=e;//直接连在后面即可

}

if(w)
{


q->next=w;

}


return c;
}


但是我输入表1为1 0 ,2 2 表二3 1,4 3时就会内存出错,纠结了一早上,请大神帮忙看看

------解决方案--------------------
http://blog.csdn.net/pfgmylove/article/details/3246105