leetcode160.相交链表
基本思路是让两个链表从“同一个起点”出发,当两点相遇时就是相交结点
m统计A的长度,n统计B的长度,让长的一方先移动m-n个结点保证两者从同一起点出发,接下来就二者同时右移找到相交结点就行
/**
* 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 m=0,n=0;
ListNode tempA=headA;
ListNode tempB=headB;
while (tempA != null) {
m++;
tempA=tempA.next;
}
while (tempB != null) {
n++;
tempB=tempB.next;
}
tempA=headA;
tempB=headB;
if(m>=n)
while(m--!=n)
tempA=tempA.next;
else
while (m++!=n)
tempB=tempB.next;
while (tempA != null && tempB != null) {
if (tempA == tempB) {
return tempA;
}
tempA=tempA.next;
tempB=tempB.next;
}
return null;
}
}