LeetCode발행일 2025. 3. 13.원본 https://blog.naver.com/jword_/223794035396 ↗

Linked List 노드 삭제 연습

Linked List 노드 삭제 연습 — #LeetCode #개발자의도구들 #링크드리스트 #LinkedList노드 only 파이썬 목표 참고 : 여기 전략 생각하...

#LeetCode#Naver Blog

#LeetCode #개발자의도구들 #링크드리스트 #LinkedList노드

​

​

  • only 파이썬
  • 목표 참고 : 여기

전략 생각하기

LeetCode(medium 19. Remove Nth Node From End of List ) 48.2%

javascript 코드 예제
                                    ⚠️ n의 크기: 1~30

✅ strp을 계산한다.
>>> 끝에서 부터 n번째 이므로 전체길이 - n 번 만큼 이동하면 대상 타겟이 있다.
>>> ex) end-3th in [1, 2, 3, 4, 5]
>>> len = 5 - 3 = 2
>>> 2번이동 1->2->3

✅ before을 누적하면서 이동한다.
>>> before을 누적하며 이동 후 제거 이후 연결해주면 끝이다.
javascript 코드 예제
                                    # Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: Optional[ListNode]
        :type n: int
        :rtype: Optional[ListNode]
        """
        total = 0

        len_tmp = head
        while len_tmp != None:
            total += 1
            len_tmp = len_tmp.next

        # if n = total
        # step = 0
        # 따로 처리

        if total == 1:
            head = None
            return head

        step = total - n

        tmp = head
        before = None
        for i in range(step):
            before = tmp
            tmp = tmp.next

        if before is not None:
            before.next = tmp.next

        return head
  • 틀렸다.
  • total = 1일때 예외처리 🙆‍♀️
  • list에서 range로 이동하는게 좋진 않다.
  • 여기서 오류 가능성이 높다.
javascript 코드 예제
                                    🤔 예외 찾아보기
>>> 찾았다. before값이 None인 경우 오류난다.
>>> 이때는 n과 total이 같을 때를 말한다.
>>> head를 다음 값으로 변경해주면된다.

​

정답코드

javascript 코드 예제
                                    # Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: Optional[ListNode]
        :type n: int
        :rtype: Optional[ListNode]
        """
        total = 0

        len_tmp = head
        while len_tmp != None:
            total += 1
            len_tmp = len_tmp.next

        # if n = total
        # step = 0
        # 따로 처리

        if total == n:
            head = head.next
            return head

        step = total - n

        tmp = head
        before = None
        for i in range(step):
            before = tmp
            tmp = tmp.next

        if before is not None:
            before.next = tmp.next

        return head
  • 정답이다.
  • t-O(n) 100% Beats / s -O(1) 88% Beats
  • 낮은 정답율에 비해서 문제가 아주 쉬웠다.