为什么链表的next还有值,为什么q只能取到头一个结点

sunny冰青 发布于 2015/09/01 16:52
阅读 263
收藏 0
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define TRUE 1
#define FASLE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef struct elemType
{
float coef;
int expn;


}ElemType;
typedef struct polyn
{
ElemType e;
struct polyn *next;
}Polyn;


Status initList(Polyn *Pn);
int listLength(Polyn Pn);
Status appendList(Polyn *Pn,ElemType e);
void initPolyn(Polyn *Pn1,Polyn *Pn2);
void polynAdd(Polyn *Pn1,Polyn *Pn2);


Status initList(Polyn *Pn)
{
Pn = (Polyn *)malloc(sizeof(Polyn));
Pn->next = NULL;
if(!Pn)
exit(OVERFLOW);
return OK;
}
int listLength(Polyn Pn)
{
Polyn *p;
int i = 0;
p = Pn.next;
    while(p!=NULL)
{
    i++;
p = p->next;
}


return i;
}
Status appendList(Polyn *Pn,ElemType e)
{
Polyn *s = (Polyn *)malloc(sizeof(Polyn));
s->next = NULL;
    s->e.coef = e.coef;
s->e.expn = e.expn;
s->next  = Pn->next;
Pn->next = s;
return OK;


}


Status traverse(Polyn Pn)
{
Polyn *p = Pn.next;
if(p==NULL)
{
  printf("NULL.......\n");
}
while(p)
{
printf("coef=%f,expn=%d\n",p->e.coef,p->e.expn);
p = p->next;

}
return OK;
}


void initPolyn(Polyn *Pn1,Polyn *Pn2)
{
ElemType e;
int i=0,n;
printf("请输入多项式1 Polyn1的项数:");
scanf_s("%d",&n);
printf("请输入多项式1 Polyn1的系数和指数,用逗号隔开!\n");
for(i=0;i<n;i++)
{
scanf_s("%f,%d",&e.coef,&e.expn);
appendList(Pn1,e);
}


printf("请输入多项式2 Polyn2的项数:");
scanf_s("%d",&n);
printf("请输入多项式2 Polyn2的系数和指数,用逗号隔开!\n");
for(i=0;i<n;i++)
{
scanf_s("%f,%d",&e.coef,&e.expn);
appendList(Pn2,e);
}
}
void polynAdd(Polyn *Pn1,Polyn *Pn2)
{
    Polyn *Pn,*p,*q,*temp;
    Pn = Pn1; 
p = Pn1->next;
q = Pn2->next;
temp = NULL;
    Pn->next = NULL;


while(p&&q)
{
   printf("current p node,coef=%f,expn=%d\n",p->e.coef,p->e.expn);
printf("current q node,coef=%f,expn=%d\n",q->e.coef,q->e.expn);
if(p->e.expn > q->e.expn)
{
Pn->next = p;

Pn = Pn->next;
Pn->next = NULL;
                printf("add  the p node,coef=%f,expn=%d\n",p->e.coef,p->e.expn);

p = p->next;
}
else if(p->e.expn < q->e.expn)
{


Pn->next = q;

Pn = Pn->next;
Pn->next = NULL;
                printf("add  the q node,coef=%f,expn=%d\n",q->e.coef,q->e.expn);

q = q->next;

}
else
{
  p->e.coef += q->e.coef;
  printf("coef to the same expn :%f\n", p->e.coef);
  if(p->e.coef!=0)
  {

Pn->next = p;
Pn = Pn->next;
Pn->next = NULL;
           
p = p->next;

temp = q;
q = q->next;
free(temp);

  }
  else
  {
temp = p;
p = p->next;
free(temp);
     
temp = q;
q = q->next;
free(temp);
  }
}
}
if(p!=NULL)
{
Pn->next = p;
printf("p!=NULL*******\n");

}
if(q!=NULL)
{
Pn->next = q;
printf("q!=NULL#######\n");
}
}
void main()
{
Polyn Pn1,Pn2;
Pn1.next = NULL;
Pn2.next = NULL;
initList(&Pn1);
initList(&Pn2);
initPolyn(&Pn1,&Pn2);
printf("\n\n");
polynAdd(&Pn1,&Pn2);
traverse(Pn1);
system("pause");


}
加载中
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部