题目描述
代码
#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 PolyInter(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);
t2 = t2->link;
t1 = t1->link;
}
else if(t1->data<t2->data) t1 = t1->link;
else 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 = PolyInter(P1,P2);
PrintPoly(PP);
return 0;
}
问题和解决方法
大规模数据测试点超时
原来进行合并时,没有考虑到两个序列是有序的。PolyInter
函数用了两个while分别循环t1和t2,每一项都进行比较,时间复杂度是O(m*n)。
如果考虑到有序,假设第一个序列第一个数字是2,第二个序列第一个数字是3,则第二个序列再往下循环是没有意义的,因为后面的节点都大于3,也就肯定不和2相等。
使用一个while循环,t1节点和t2节点都从头开始,比较二者大小,决定让哪一个往下走,则可以实现时间复杂度为O(m+n)。