boolcrossLists2(ListNode* head1, ListNode* head2){ if (!head1 || !head2 ) returntrue; ListNode* dhead = new ListNode(-1, head1); ListNode* needle = dhead; // move needle to the end of head1 while (needle->next){ needle = needle->next; } // link the tail of head1 to the head of head2; needle->next = head2;
// check if there exists a loop return hasCycle(head1); }
其中hasCycle():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
boolhasCycle(ListNode* head){ if (!head) returnfalse; ListNode* fast = head; ListNode* slow = head;
while(fast && slow){ fast = fast->next; slow = slow->next;
if (fast) fast = fast->next; // 先判断移动后的fast是否非空 if (fast && fast==slow) returntrue; } returnfalse; }