Skip to content

Commit d0dbce0

Browse files
committed
Remove nth node from end of list
1 parent 004dce7 commit d0dbce0

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package leetcode_study
2+
3+
class ListNode(var `val`: Int) {
4+
var next: ListNode? = null
5+
}
6+
7+
// 힌트 참고
8+
// Time Complexity: O(L) where L is the length of the linked list
9+
// Space Complexity: O(1) since we are using only a constant amount of space
10+
class Solution {
11+
fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
12+
var left = head
13+
var right = head
14+
var step = n
15+
while (step-- > 0) {
16+
right = right?.next
17+
}
18+
if (right == null) {
19+
return head?.next // n이 리스트의 길이와 같을 때, 즉 첫 번째 노드를 제거해야 하는 경우
20+
}
21+
while (right?.next != null) {
22+
left = left?.next
23+
right = right.next
24+
}
25+
26+
left?.next = left?.next?.next
27+
return head
28+
}
29+
}
30+
31+

0 commit comments

Comments
 (0)