題目
如何判斷兩個有環單鏈表是否相交?相交的話返回第一個相交的節點,不想交的話返回空。如果兩個鏈表長度分別為N和M,請做到時間復雜度O(N+M),額外空間復雜度O(1)。
給定兩個鏈表的頭結點head1和head2,請返回一個bool值代表它們是否相交。
思路
一共有三種相交的情況:
- 在入環的節點相交
- 在入環的節點之前相交
- 在環中相交
解題的關鍵在于先拿到如環的節點,然后即可對三種情況進行判斷
答案
ListNode* intersectNode(ListNode *head) {
ListNode *slowNode = head;
ListNode *fastNode = head;
while (fastNode->next != NULL && fastNode->next->next != NULL) {
fastNode = fastNode->next->next;
slowNode = slowNode->next;
if (slowNode == fastNode) {
fastNode = head;
while (fastNode != slowNode) {
fastNode = fastNode->next;
slowNode = slowNode->next;
}
return slowNode;
}
}
return NULL;
}
bool chkInter(ListNode* head1, ListNode* head2, int adjust0, int adjust1) {
ListNode *intersectNode1 = intersectNode(head1);
ListNode *intersectNode2 = intersectNode(head2);
// 第一種情況:在環的入口點或者環入口點之前就已經相交
if (intersectNode1 == intersectNode2) {
return true;
}
// 第二種情況:在環中相交
ListNode *current = intersectNode1;
while (1) {
current = current->next;
if (current == intersectNode1) {
break;
} else if (current == intersectNode2){
return true;
}
}
return false;
}