File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 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+
You can’t perform that action at this time.
0 commit comments