Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
分析:
找到两个链表的交点。为降低复杂度,如果两个链表长度不同,可以先将较长的链表向后移动差值距离,再依次进行比较,没有相等的则返回NULL。
/**
* 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) {
if(!headA || !headB)
return NULL;
int lenA = 0;
int lenB = 0;
lenA = getLen(headA);
lenB = getLen(headB);
if(lenA < lenB)
{
for(int i=0; i<lenB-lenA; i++)
headB = headB->next;
}
else
{
for(int i=0; i<lenA-lenB; i++)
headA = headA->next;
}
while(headA && headB && headA!=headB)
{
headA = headA->next;
headB = headB->next;
}
if(headA && headB)
return headA;
else
return NULL;
}
int getLen(ListNode *head)
{
int len = 0;
while(head)
{
len++;
head = head->next;
}
return len;
}
};