LeetCode 160 相交链表
一:题目描述
二:题目解答
解法一:链表长度分析
我们求一个相交链表,就要找出相交链表有什么特征。我们要求相交点,首先要明确的一点就是,这个点有什么特殊的。我们分析发现,相交点后面的都是两条链表共有的,也就是相交点后面都是一样的,这当然也包括长度。那么两条相交链表不同的长度就只有相交之前的了。我们可以首先把两条链表指向的长度变成一样长,然后再一起移动指针,当指向的节点相等时,就是第一个相交点。(若没有相交点,则最后指向的相等的节点为null,也可直接返回)。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null||headB==null) return null;
int lengthA=getLength(headA);
int lengthB=getLength(headB);
ListNode tmpA=headA,tmpB=headB;
while(lengthA>lengthB){
lengthA--;
tmpA=tmpA.next;
}
while(lengthB>lengthA){
lengthB--;
tmpB=tmpB.next;
}
while(tmpA!=tmpB){
tmpA=tmpA.next;
tmpB=tmpB.next;
}
return tmpA;
}
public int getLength(ListNode head){
ListNode tmp=head;
int length=0;
while(tmp!=null){
tmp=tmp.next;
length++;
}
return length;
}
}
解法二:指针追逐
我们在判断一个单链表是否有环的时候运用了快慢指针的方法,这也是一种指针追逐的方法。但是它是由于存在环快慢指针就肯定会相遇。那么对于我们这道题来说,我们怎么样让指针一直在动而不是移动到结尾就结束呢。经过分析,当一个指针移动到结尾时,那么我们就把它重置到另一个链表的开头。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null||headB==null) return null;
ListNode tmpA=headA,tmpB=headB;
while(tmpA!=tmpB){
tmpA=(tmpA==null?headB:tmpA.next);
tmpB=(tmpB==null?headA:tmpB.next);
}
return tmpA;
}
}