접근
- 두 커서(Two pointer) 개념을 링크드 리스트 문제에 적용시켜 푸는 문제
- 먼저 간 커서를 n 번 순회시켰을 때, None 인 경우와 그렇지 않은 경우를 모두 생각하여 솔루션을 작성해야 함
- 가능한 케이스를 모두 면밀히 고민해 볼 필요가 있음
솔루션
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
cur_left, cur_right = head, head
answer = cur_left
for i in range(n):
cur_right = cur_right.next
if cur_right is None:
return cur_left.next
while cur_right.next:
cur_right = cur_right.next
cur_left = cur_left.next
cur_left.next = cur_left.next.next
return answer
'컴퓨터공학 & 정보통신 > 알고리즘 문제 풀이' 카테고리의 다른 글
[LeetCode] 17. Letter Combinations of a Phone Number (0) | 2023.03.20 |
---|---|
[LeetCode] 22. Generate Parentheses (0) | 2023.03.20 |
[LeetCode] 2. Add Two Numbers (0) | 2023.03.13 |
[GeeksforGeeks] Special array reversal (0) | 2023.02.22 |
[LeetCode] 1971. Find if Path Exists in Graph (0) | 2023.02.15 |