본문 바로가기

⏳ 알고리즘/python 알고리즘 문제 풀이

리트코드 - 19.Remove Nth Node From End of List

문제

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

 

Remove Nth Node From End of List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

코드

노드를 삭제하는 경우 3가지

  • head 삭제
  • 마지막 노드 삭제
  • 중간 노드 삭제
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

def calcul_length(self):
        count = 0
        while self:
            count += 1
            self = self.next
        return count
    
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        node = head
        current = node

        # 연결리스트의 길이가 1이고, 지워야할 노드가 1번일 경우
        if calcul_length(head) == 1 and n == 1:
            head.val = ''
            return head

        count = calcul_length(head)-n
        # 1번 노드를 지워야할 경우
        if count == 0:
            return head.next

        # 그 이외 경우
        else:
            while count > 1:
                if current.next:
                    current = current.next
                    count -= 1
                else: 
                    return current
            current.next = current.next.next
    
        return node