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.
Notes:
- If the two linked lists have no intersection at all, return
null
. - The linked lists must retain their original structure after the function returns.
- You may assume there are no cycles anywhere in the entire linked structure.
- Your code should preferably run in O(n) time and use only O(1) memory.
解题关键
试想一下,如果这个链表A和链表B的长度相同,我们是不是就可以直接对两个链表同时进行遍历,只要发现两个链表的某一个部分相同了,这个相同部分就是c1,BUT,现在这两个链表长度并不是相同,因此,我们需要想办法保证两个链表从后向前,有一部分长度是相同的(即都为短链的长度),如题目中,A :a1->a2->c1->c2->c3,长度为5,然而,B:b1->b2->b3->c1->c2->c3, 长度为6,因此我们可以让B链表,从b2开始,到最后,保证长度与短的链A的长度相同即可。
解题思路
1、如果有一个链表为空,返回结果为空
2、获取两个链表的长度(同时判断最后一个元素是不是相同,两个链表的最后一个元素不同,则返回空)
3、对较长的链表,指针后移,保证其剩余部分的总长度等于短链表的长度
4、同时遍历两个链表,直到两个节点元素相同,该节点即为交集,否则返回结果为空
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
//其中有一个为空
if(!headA || ! headB)
return NULL;
int len1=0;
int len2=0;
int i = 0;
struct ListNode *result = NULL;
struct ListNode *p = headA;
struct ListNode *q = headB;
//获取两个链表的长度
while(p)
{
len1++;
p = p->next;
}
while(q)
{
len2++;
q = q->next;
}
//若最后一个元素不相同,则没有交集
if(p != q)
return false;
//判断哪个更长(将长链后移保证其长度与短链相同)
if(len1 >=len2)
{
for(i=0;i<len1-len2;i++)
headA = headA->next;
}else{
for(i=0;i<len2-len1;i++)
headB = headB->next;
}
//最后相同长度同时后移,并判断
while(headA && headB)
{
if(headA == headB)
{
result = headA;
break;
}
headA = headA->next;
headB = headB->next;
}
return result;
}