Skip to content

Commit 2f2b61a

Browse files
author
이연수
committed
remove nth node from end of list
1 parent 28cef36 commit 2f2b61a

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+
package leetcode_study
2+
3+
/*
4+
* 끝에서 n 번째 노드를 제거하는 문제
5+
* 예외 상황이 발생하는 Case를 나눠 문제 해결
6+
* 시간 복잡도 : O(n)
7+
* -> node list를 순회하며 배열에 담는 과정
8+
* 공간 복잡도 : O(n)
9+
* -> 각 node를 담을 list 공간
10+
* */
11+
fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
12+
val tempNodeList = mutableListOf<ListNode>()
13+
var currentHead = head
14+
while (currentHead != null) {
15+
tempNodeList.add(currentHead)
16+
currentHead = currentHead.next
17+
}
18+
19+
val preIndex = tempNodeList.size - n - 1
20+
val postIndex = tempNodeList.size - n + 1
21+
22+
if (preIndex < 0) {
23+
if (tempNodeList.size == 1) {
24+
return null
25+
}
26+
return tempNodeList[postIndex]
27+
} else if (postIndex == tempNodeList.size) {
28+
tempNodeList[preIndex].next = null
29+
return head
30+
} else {
31+
tempNodeList[preIndex].next = tempNodeList[postIndex]
32+
}
33+
return head
34+
}

0 commit comments

Comments
 (0)