/**
* 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 cur1 = headA;
ListNode cur2 = headB;
int len1 = 1, len2 = 1;
while (cur1.next != null) {
cur1 = cur1.next;
len1++;
}
while (cur2.next != null) {
cur2 = cur2.next;
len2++;
}
cur1 = headA;
cur2 = headB;
if (len1 > len2) {
for (int i = 0; i < len1 - len2; i++) {
cur1 = cur1.next;
}
} else {
for (int i = 0; i < len2 - len1; i++) {
cur2 = cur2.next;
}
}
while (cur1 != null && cur2 != null) {
if (cur1 == cur2) {
return cur1;
}
cur1 = cur1.next;
cur2 = cur2.next;
}
return null;
}
}
Intersection of Two Linked Lists
最新推荐文章于 2022-01-22 17:00:38 发布