1.题目
给你两个单链表的头节点
headA
和headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回null
。
2.解题思路
法一:
先计算两个链表长度,计算长度差gap,将指向长度比较长的链表的指针先移动gap个单位,然后让指向两个链表的指针p1,p2分别从链头位置同时开始移动,判断p1,p2是否有相同的时候。
法二:
3.代码
/**
* 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) {
int l1=0,l2=0;
ListNode* p1=headA;
ListNode* p2=headB;
while(p1){
l1++;
p1=p1->next;
}
p1=headA;
while(p2){
l2++;
p2=p2->next;
}
p2=headB;
if(l1>l2){
int gap=l1-l2;
while(gap-- and p1){
p1=p1->next;
}
}else{
int gap=l2-l1;
while(gap-- and p2){
p2=p2->next;
}
}
while(p1){
if(p1==p2){
return p1;
}
p1=p1->next;
p2=p2->next;
}
return NULL;
}
};