题目描述
代码
#include <stdio.h>
#include <malloc.h>
typedef struct PolyNode *Polynomial;
struct PolyNode{
int data;
Polynomial link;
};
void Attach(int d, Polynomial *pRear)
{
Polynomial p;
p = (Polynomial)malloc(sizeof(struct PolyNode));
p->data = d;
p->link = NULL;
(*pRear)->link = p;
*pRear = p;
}
Polynomial PolyRead()
{
Polynomial front,rear,t;
int m;
front = (Polynomial)malloc(sizeof(struct PolyNode));
front->link = NULL;
rear = front;
scanf("%d",&m);
Attach(m, &rear);
while(m+1){
scanf("%d",&m);
Attach(m, &rear);
}
t = front; front = front->link; free(t);
return front;
}
Polynomial PolyLink(Polynomial P1, Polynomial P2)
{
Polynomial t1, t2, front, rear,t;
t1 = P1;t2 = P2;
front = (Polynomial)malloc(sizeof(struct PolyNode));
front->link = NULL;
rear = front;
while((t1->data+1)&&(t2->data+1)){
if(t1->data<t2->data){
Attach(t1->data,&rear);
t1 = t1->link;
}
else if(t1->data==t2->data){
Attach(t1->data,&rear);
Attach(t1->data,&rear);
t2 = t2->link;
t1 = t1->link;
}
else{
Attach(t2->data,&rear);
t2 = t2->link;
}
}
while(t1->data+1){
Attach(t1->data,&rear);
t1 = t1->link;
}
while(t2->data+1){
Attach(t2->data,&rear);
t2 = t2->link;
}
if(front->link==NULL)Attach(-1, &rear);
t = front;
front = front->link;
free(t);
return front;
}
void PrintPoly(Polynomial P){
Polynomial t;
t = P;
if(t->data==-1) printf("NULL");
else{
int m = 0;
while(t){
if(m)printf(" ");
m=1;
printf("%d",t->data);
t = t->link;
}
}
}
int main()
{
Polynomial P1, P2, PP;
P1 = PolyRead();
P2 = PolyRead();
PP = PolyLink(P1,P2);
PrintPoly(PP);
return 0;
}
问题和改正
1.段错误
引用空指针时会发生段错误。
出现错误的PrintPoly函数
void PrintPoly(Polynomial P){
Polynomial t;
t = P;
if(t->data==-1) printf("NULL");
else{
int m = 0;
while(t->data+1){
if(m)printf(" ");
m=1;
printf("%d",t->data);
t = t->link;
}
}
}
while(t->data+1)
经过PolyLink函数处理后,这里的t链表的最后一个节点的data不是-1,而是正数。所以到最后一个节点后,循环不会停止,t会继续指向NULL,循环体中会引用这个空指针。
while循环的判断条件直接改为while(t->data+1)
。
2.有并列测试点错误
非降序序列,相同的数不会合并,而是排在一起。比如输入1 -1
和1 -1
,输出应该是1 1
而不是1