[LeetCode]Remove Nth Node From End of List

2023. 4. 11. 21:37·SW개발/코딩테스트

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

 

Remove Nth Node From End of List - LeetCode

Can you solve this real interview question? Remove Nth Node From End of List - Given the head of a linked list, remove the nth node from the end of the list and return its head.   Example 1: [https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg]

leetcode.com

 

문제 분석

주어진 링크드 리스트에서 뒤에서 n번째에 해당하는 노드를 제거하는 문제입니다.

 

처음 시도한 답안

접근 방법

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        left = right = head
        # right를 미리 n칸 만큼 앞으로 전진
        # 이렇게 되면 right가 끝까지 가는 경우, left의 다음 노드가 삭제 대상으로 간주 가능.
        for _ in range(n):
            right = right.next
        
        # right가 없는 노드라면(n이 링크드 리스트 길이인 경우) 맨 처음 노드가 삭제 대상.
        if not right:
            return left.next
        
        while right.next:
            left = left.next
            right = right.next
        # right가 끝까지 도달하면, left의 다음 노드가 삭제 대상임.
        left.next = left.next.next

        return head
  1. left, right 투 포인터를 활용합니다.
  2. right 포인터를 미리 n 칸만큼 전진시킵니다. 
  3. 만약 right 노드가 비어있다면 맨 처음 노드가 삭제 대상입니다.
  4. right가 끝에 도달할 때까지, left, right를 한칸씩 이동합니다.
  5. right가 끝에 도달하면 left의 다음 노드가 삭제 대상이 됩니다. 
  6. next.next를 이용해 삭제 대상 노드를 제거합니다.

느리게가는 left 포인터, 미리 n칸 전진해있는 right 포인터를 활용해 One Pass로 문제를 해결할 수 있습니다.

 

728x90

'SW개발 > 코딩테스트' 카테고리의 다른 글

[LeetCode]Swap Nodes in Pairs  (0) 2023.04.13
[LeetCode]Generate Parentheses  (0) 2023.04.12
[LeetCode]Letter Combinations of a Phone Number  (0) 2023.04.10
[LeetCode]3Sum  (0) 2023.04.09
[LeetCode]Container With Most Water  (0) 2023.04.08
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Swap Nodes in Pairs
  • [LeetCode]Generate Parentheses
  • [LeetCode]Letter Combinations of a Phone Number
  • [LeetCode]3Sum
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (307)
      • SW개발 (303)
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (1)
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    배공파용
    배달
    트리 #AVL #알고리즘 #자료구조
    django
    음식
    라이프 스타일
    컨트리뷰터
    Contributor
    어플리케이션
    플레이스토어
    g
    오픈소스
    배달비 공유
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Leffe_pt
[LeetCode]Remove Nth Node From End of List
상단으로

티스토리툴바