ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 19. Remove Nth Node From End of List
    Leetcode 2021. 5. 10. 15:38

    Given the head of a linked list, remove the nth node from the end of the list and return its head.

    Follow up: Could you do this in one pass?

     

    Example 1:

    Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]

    Example 2:

    Input: head = [1], n = 1 Output: []

    Example 3:

    Input: head = [1,2], n = 1 Output: [1]

     

    Constraints:

    • The number of nodes in the list is sz.
    • 1 <= sz <= 30
    • 0 <= Node.val <= 100
    • 1 <= n <= sz
    # 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: ListNode
            :type n: int
            :rtype: ListNode
            """
            
            l = 0
            cur = head
            while cur:
                cur = cur.next
                l +=1
    
            target = l - n
            l = 0
            
            if target == 0:
                return head.next
            
            cur = head
            
            while cur:
                if l == target-1:
                    cur.next = cur.next.next
                cur = cur.next
                l+=1
            return head
            

    - 두 번 선회하다보니 느릴줄 알았는데, 16 ms, faster than 91.44% of Python 가 나왔다.

    'Leetcode' 카테고리의 다른 글

    21. Merge Two Sorted Lists  (0) 2021.05.11
    20. Valid Parentheses  (0) 2021.05.10
    18. 4Sum  (0) 2021.05.10
    17. Letter Combinations of a Phone Number  (0) 2021.05.10
    16. 3Sum Closest  (0) 2021.05.06
Designed by Tistory.