Skip to content

Commit 65c15e0

Browse files
committed
Time: 1 ms (15.51%), Space: 36.1 MB (18.99%) - LeetHub
1 parent 2bc146f commit 65c15e0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Example:
3+
* var li = ListNode(5)
4+
* var v = li.`val`
5+
* Definition for singly-linked list.
6+
* class ListNode(var `val`: Int) {
7+
* var next: ListNode? = null
8+
* }
9+
*/
10+
class Solution {
11+
private fun remove(head: ListNode?, n: Int, i: Int): Pair<ListNode?, Int> {
12+
if (head == null) {
13+
return null to i
14+
}
15+
val (next, lastIndex) = remove(head.next, n, i + 1)
16+
17+
if (lastIndex - i == n) {
18+
return next to lastIndex
19+
}
20+
head.next = next
21+
return head to lastIndex
22+
}
23+
24+
fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
25+
if (head == null) {
26+
return null
27+
}
28+
val (next, lastIndex) = remove(head, n, 0)
29+
if (lastIndex == n) {
30+
return next
31+
}
32+
return head
33+
}
34+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy