![题目]()
解题思路:如果两个链表在某一点相交,那么那一点之后的node也都会相同,长度也相同。所以,我们先遍历获取对应每一条链表的长度,然后让长的链表先走两个链表长度之差的距离,然后再同时起步,每个节点进行对比,能不能找到相同的。
/**
* 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) {
if (headA==null || headB==null) return null;
ListNode dummy_head1 = new ListNode();
ListNode dummy_head2 = new ListNode();
dummy_head1.next = headA;
dummy_head2.next = headB;
ListNode p = dummy_head1;
ListNode q = dummy_head2;
int count1 = 0;
int count2 = 0;
while(p.next!=null){
count1++;
p = p.next;
}
while(q.next!=null) {
count2++;
q = q.next;
}
p = dummy_head1;
q = dummy_head2;
while(count1>count2)
{
p = p.next;
count1--;
}
while(count1<count2)
{
q = q.next;
count2--;
}
while(p.next!=null){
p = p.next;
q = q.next;
if(p == q){
return p;
}
}
return null;
}
}