Skip to content

Commit bab419c

Browse files
committed
1 parent 2e39614 commit bab419c

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package leetcode.`intersection-of-two-linked-lists`
2+
3+
import ListNode
4+
import org.junit.Test
5+
import util.ListNodeUtil
6+
7+
class Solution {
8+
fun getIntersectionNode(headA: ListNode?, headB: ListNode?): ListNode? {
9+
var pA = headA
10+
while (pA?.next != null) {
11+
if (headB == pA) return headB
12+
pA = pA.next
13+
}
14+
if (pA == headB) return headB
15+
pA?.next = headA
16+
val endA = pA
17+
var slowP = headB
18+
var fastP = headB
19+
while ((slowP != fastP && slowP != null && fastP != null) || slowP == headB) {
20+
slowP = slowP?.next
21+
fastP = fastP?.next?.next
22+
}
23+
slowP = headB
24+
while ((slowP != fastP && slowP != null && fastP != null) || slowP == headB) {
25+
slowP = slowP?.next
26+
fastP = fastP?.next
27+
}
28+
endA?.next = null
29+
return fastP
30+
}
31+
32+
@Test
33+
fun test(){
34+
val list1 = ListNodeUtil.generate(intArrayOf(8,4,5))
35+
}
36+
}

src/main/kotlin/util/ListNodeUtil.kt

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,20 @@
11
package util
22

3-
object ListNodeUtil {
4-
fun generate(){
3+
import ListNode
54

5+
object ListNodeUtil {
6+
fun generate(intArray: IntArray): ListNode {
7+
lateinit var head: ListNode
8+
var tmp: ListNode? = null
9+
intArray.forEachIndexed { index, i ->
10+
if (index == 0) {
11+
head = ListNode(i)
12+
tmp = head
13+
} else {
14+
tmp?.next = ListNode(i)
15+
tmp = tmp?.next
16+
}
17+
}
18+
return head
619
}
720
}

0 commit comments

Comments
 (0)