60 lines
1.3 KiB
Java
60 lines
1.3 KiB
Java
/*
|
|
* @lc app=leetcode id=160 lang=java
|
|
*
|
|
* [160] Intersection of Two Linked Lists
|
|
*/
|
|
|
|
// @lc code=start
|
|
/**
|
|
* 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;
|
|
}
|
|
int la = len(headA), lb = len(headB);
|
|
ListNode cura = headA, curb = headB;
|
|
if(la < lb) {
|
|
// move curB
|
|
for(int i=0; i<lb-la; i++) {
|
|
curb = curb.next;
|
|
}
|
|
} else {
|
|
// move curA
|
|
for(int i = 0; i<la-lb; i++) {
|
|
cura = cura.next;
|
|
}
|
|
}
|
|
ListNode r = null;
|
|
while(cura!=null) {
|
|
if(cura == curb) {
|
|
r = cura;
|
|
break;
|
|
}
|
|
cura = cura.next;
|
|
curb = curb.next;
|
|
}
|
|
return r;
|
|
}
|
|
|
|
private int len(ListNode head) {
|
|
int l = 0;
|
|
while(head != null) {
|
|
l++;
|
|
head = head.next;
|
|
}
|
|
return l;
|
|
}
|
|
}
|
|
// @lc code=end
|
|
|