查找两个链表,有重合的那个节点。
注意不要比链表中节点的值,而要比较指针
将两个链表的长度统一,然后一边遍历即可。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int getListLength(ListNode * head)
{
int res = 0;
while(head)
{
res++;
head = head->next;
}
return res;
}
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == NULL || headB == NULL) return NULL;
int lenA = getListLength(headA);
int lenB = getListLength(headB);
// 这里一定要有=,否则两个长度相同的链表a b都指向同一个链表
ListNode* a = lenA >= lenB ? headA : headB;
ListNode* b = lenA < lenB ? headA : headB;
int c = abs(lenA - lenB);
ListNode * res = NULL;
while (a && b)
{
if (c > 0)
{
--c;
a = a->next;
continue;
}
if (!res && a == b)
{
res = a;
}
if (res && a != b)
{
res = NULL;
}
a = a->next;
b = b->next;
}
return res;
}
};
Runtime: 52 ms, faster than 98.01% of C++ online submissions for Intersection of Two Linked Lists.
Memory Usage: 16.8 MB, less than 41.28% of C++ online submissions for Intersection of Two Linked Lists.
当然还有很多淫巧的代码。
https://leetcode.com/problems/intersection-of-two-linked-lists/discuss/49799/Simple-C%2B%2B-solution-(5-lines)
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *cur1 = headA, *cur2 = headB;
while(cur1 != cur2){
cur1 = cur1?cur1->next:headB;
cur2 = cur2?cur2->next:headA;
}
return cur1;
}
这种方式实际上就是将两个链表合并成两段,遍历
A -> B
B -> A
这样长度就一样了,然后只需要遍历到最后面,有相同的时候跳出循环即可。