两个有序链表(相邻元素可能相同),找出他们的交集,并把结果放到另一链表中,代码如下:
typedef struct Node* pNode;
struct Node
{
int val;
struct Node *next;
};
pNode merge(pNode head1, pNode head2)
{
pNode head = NULL;
pNode p1 = head1;
pNode p2 = head2;
pNode p3 = NULL;
pNode p4 = NULL;
if (NULL == p1 || NULL == p2)
{
return NULL;
}
/*先找出相交的第一个元素,并作为存储交集链表的头结点*/
while (p1 && p2)
{
if (p1->val == p2->val)
{
head = (pNode)malloc(sizeof(struct Node));
head->val = p1->val;
head->next = NULL;
p1 = p1->next;
p2 = p2->next;
break;
}
else if (p1->val > p2->val)
{
while (p2->next != NULL && p2->val == p2->next->val)
{
p2 = p2->next;
}
p2 = p2->next;
}
else
{
while (p1->next != NULL && p1->val == p1->next->val)
{
p1 = p1->next;
}
p1 = p1->next;
}
}
p3 = p4 = head;
while (p1 && p2)
{
if (p1->val == p2->val && p1->val != p3->val && p2->val != p3->val)
{
p4 = (pNode)malloc(sizeof(struct Node));
p4->next = NULL;
p4->val = p1->val;
p3->next = p4;
p3 = p4;
p1 = p1->next;
p2 = p2->next;
}
else if (p1->val > p2->val)
{
while (p2->next != NULL && p2->val == p2->next->val)
{
p2 = p2->next;
}
p2 = p2->next;
}
else
{
while (p1->next != NULL && p1->val == p1->next->val)
{
p1 = p1->next;
}
p1 = p1->next;
}
}
return head;
}