File tree Expand file tree Collapse file tree 1 file changed +33
-2
lines changed
remove-nth-node-from-end-of-list Expand file tree Collapse file tree 1 file changed +33
-2
lines changed Original file line number Diff line number Diff line change @@ -68,14 +68,45 @@ def check_order_from_end(curr):
6868
6969 return prev .next
7070
71+ def removeNthFromEnd_length (self , head : Optional [ListNode ], n : int ) -> Optional [ListNode ]:
72+ """
73+ [Complexity]
74+ - TC: O(n)
75+ - SC: O(1)
76+
77+ [Approach]
78+ linked list의 전체 길이를 구하고, head에서부터 (길이 - n - 1) 번 전진하여 node를 건너뛰면 된다.
79+ (2 pass)
80+ """
81+ # linked list의 length 구하기
82+ length = 0
83+ curr = head
84+ while curr :
85+ length += 1
86+ curr = curr .next
87+
88+ # length == n라면, head를 제거
89+ if length == n :
90+ return head .next
91+
92+ # length - n - 1 번 이동
93+ curr = head
94+ for _ in range (length - n - 1 ):
95+ curr = curr .next
96+
97+ # node 제거
98+ curr .next = curr .next .next
99+
100+ return head
101+
71102 def removeNthFromEnd (self , head : Optional [ListNode ], n : int ) -> Optional [ListNode ]:
72103 """
73104 [Complexity]
74- - TC: O(len )
105+ - TC: O(n )
75106 - SC: O(1)
76107
77108 [Approach]
78- slow, fast의 two pointer를 이용해 반복문으로 풀 수 있다.
109+ slow, fast의 two pointer를 이용해 반복문으로 풀 수 있다. (1 pass)
79110 1. fast를 n 번 전진
80111 2. fast가 끝에 도달한 경우, 첫 번째 node를 제거해야하므로 head.next 반환
81112 3. 현재 fast의 위치에서 slow와 fast를 함께 전진하면, fast가 끝에 도달할 때 slow는 뒤에서부터 n + 1번째 node임
You can’t perform that action at this time.
0 commit comments