파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 9. 28. 23:45

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

개념 자체는 간단쓰.
리스트를 순회하면서 크기를 일단 구하고 삭제할 노드를 제거 한 뒤 이어 붙이면 된다.

근데 구현은 쪼깨 힘드네 =_=

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        
        l = 0
        h = head
        while h:
            h = h.next
            l += 1
        c = l - n + 1
        
        if n == l:            
            return head.next
        
        cnt = 1
        pre = None
        curr = head
        while curr:
            if cnt == c:
                pre.next = curr.next
                break
            cnt += 1
            pre = curr
            curr = curr.next
        
        return head
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.09.30
Today's Challenge  (0) 2022.09.29
Today's Challenge  (0) 2022.09.27
Today's Challenge  (0) 2022.09.25
Today's Challenge  (0) 2022.09.24
Comments