Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 65c15e0

Browse files
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)

AltStyle によって変換されたページ (->オリジナル) /