一.判定两个链表是否相交,但是链表可能带环
1.分别求两个链表的环的入口
2.如果两个链表的不带环,直接使用之前的方式判定相交
3.如果一个带环一个不带环,那么直接返回不相交
4.如果两个链表都带环
a)如果这两个入口点重合,说明相交,并且是环外相交
b)如果从一个入口点出发,绕环一周,能到达第二个入口,说明也相交,并且是环上相交
c)如果不是上面两种情况,那么也证明不相交
int HasCrossWithCycle(LinkNode* head1, LinkNode* head2){
if(head1 == NULL && head2 == NULL ){
//空链表
return 0;
}
LinkNode* cycle1 = GetCycleEntry(head1);
LinkNode* cycle2 = GetCycleEntry(head2);
if(cycle1 == NULL && cycle2 == NULL) {
return HasCross(head1,head2) != NULL ? 1 : 0;
}
else if(cycle1 != NULL && cycle2 != NULL){
if(cycle1 == cycle2){
return 1;
}
LinkNode* cur = cycle1->next;
while(cur != cycle1){
if(cur == cycle2){
return 1;
}
cur = cur->next;
}
return 0;
}else {
return 0;
}
return 0;
}
二.求两个有序链表的交集
LinkNode* UnionSet(LinkNode* head1, LinkNode* head2){
if(head1 == NULL || head2 == NULL){
//空链表
return NULL;
}
LinkNode* cur1 = head1;
LinkNode* cur2 = head2;
LinkNode* new_head = NULL;
LinkNode* new_tail = NULL;
while(cur1!=NULL && cur2!=NULL){
if(cur1->data < cur2->data){
cur1 = cur1->next;
}else if(cur1->data > cur2->data){
cur2 = cur2->next;
}else {
if(new_head == NULL){
new_head = CreatNode(cur1->data);
new_tail = new_head;
}else {
new_tail->next = CreatNode(cur1->data);
new_tail = new_tail->next;
}
}
cur1 = cur1->next;
cur2 = cur2->next;
}
return new_head;
}