思路1:
分别算两个链表的长度,然后遍历较长的链表,让他们的站在同一起跑线上
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int len = 0;
ListNode tmp = headA;
while(tmp != null){
tmp = tmp.next;
len++;
}
tmp = headB;
while(tmp != null){
tmp = tmp.next;
len--;
}
if(len < 0){
tmp = headA;
headA = headB;
headB = tmp;
len = -len;
}
while(len > 0){
headA = headA.next;
len--;
}
while(headA != null && headB != null){
if(headA == headB){
return headA;
}
headA = headA.next;
headB = headB.next;
}
return null;
}
}
思路2:
就是让两个链表一起遍历,当一个链表遍历到终点的时候,让它重新成为另一个链表的起点,直到二者相逢。
如果二者没有交点,那么A+B=B+A 会同时等于Null
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode h1 = headA;
ListNode h2 = headB;
while(h1 != h2){
h1 = h1 == null? headB:h1.next;
h2 = h2 == null? headA:h2.next;
}
return h1;
}
}