一.判定兩個鏈表是否相交,但是鏈表可能帶環
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;
}