problem
with knowing length
class Solution {
fun getIntersectionNode(headA:ListNode?, headB:ListNode?):ListNode? {
var _headA = headA
var _headB = headB
var lenA = 0
var lenB = 0
while (_headA != null) {
lenA++
_headA = _headA?.next
}
while (_headB != null) {
lenB++
_headB = _headB?.next
}
_headA = headA
_headB = headB
while (_headA != _headB) {
if (lenA > lenB) {
lenA--
_headA = _headA?.next
} else if (lenA < lenB) {
lenB--
_headB = _headB?.next
} else {
_headA = _headA?.next
_headB = _headB?.next
}
}
return _headA
}
}
without knowing length
class Solution {
fun getIntersectionNode(headA:ListNode?, headB:ListNode?):ListNode? {
var _headA = headA
var _headB = headB
while (_headA != _headB) {
_headA = if (_headA == null) headB else _headA?.next
_headB = if (_headB == null) headA else _headB?.next
}
return _headA
}
}