Skip to content

Commit 025a7ee

Browse files
committed
Add a problem 'Reverse Linked List'
1 parent 533328f commit 025a7ee

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
package io.github.juchanei.leetcodeJava
2+
3+
import org.assertj.core.api.BDDAssertions.then
4+
import org.junit.jupiter.api.Test
5+
6+
// https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/560/
7+
class ReverseLinkedList {
8+
data class ListNode(val `val`: Int, val next: ListNode?)
9+
10+
fun reverseList(head: ListNode?): ListNode? =
11+
reverseList(head = head, acc = null)
12+
13+
private tailrec fun reverseList(head: ListNode?, acc: ListNode?): ListNode? =
14+
if (head == null) {
15+
acc
16+
} else {
17+
reverseList(
18+
head = head.next,
19+
acc = ListNode(head.`val`, acc)
20+
)
21+
}
22+
23+
@Test
24+
fun example1() {
25+
val l = listOf(1, 2)
26+
27+
val actual = reverseList(l.toListNode())
28+
29+
then(actual.toList()).isEqualTo(l.reversed())
30+
}
31+
32+
@Test
33+
fun example2() {
34+
val l = emptyList<Int>()
35+
36+
val actual = reverseList(l.toListNode())
37+
38+
then(actual.toList()).isEqualTo(l.reversed())
39+
}
40+
41+
@Test
42+
fun example3() {
43+
val l = listOf(1)
44+
45+
val actual = reverseList(l.toListNode())
46+
47+
then(actual.toList()).isEqualTo(l.reversed())
48+
}
49+
50+
@Test
51+
fun example4() {
52+
val l = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
53+
54+
val actual = reverseList(l.toListNode())
55+
56+
then(actual.toList()).isEqualTo(l.reversed())
57+
}
58+
59+
private fun List<Int>.toListNode(): ListNode? {
60+
if (isEmpty()) return null
61+
return ListNode(first(), drop(1).toListNode())
62+
}
63+
64+
private fun ListNode?.toList(): List<Int> {
65+
val result = mutableListOf<Int>()
66+
67+
var node: ListNode? = this
68+
while (true) {
69+
if (node == null) break
70+
result.add(node.`val`)
71+
node = node.next
72+
}
73+
74+
return result
75+
}
76+
}

0 commit comments

Comments
 (0)