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