双指针法:
时间复杂度:
空间复杂度:
两个指针把两个链表都走一遍,必定在重合点相遇
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
ListNode* head1 = headA;
ListNode* head2 = headB;
while (head1 != head2) {
head1 = head1 ? head1->next : headB;
head2 = head2 ? head2->next : headA;
}
return head1;
}
};