[Python 으로 푸는 Leetcode]19. Remove Nth Node From End of List

느린 개발자·2020년 12월 22일
0

Coding Test

목록 보기
13/21

📌Problem

Given the head of a linked list, remove the nthn^{th} 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

leetcode 에서 풀기


📝Solution

✏️ Two pointers

# 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: ListNode, n: int) -> ListNode:
        
        dummy=ListNode(-1)
        dummy.next=head
        
        back=dummy
        front=dummy
        
        for i in range(n): #Move front cursor by 'n'
            front=front.next
            
        while front.next!=None: # Move front, back cursor by 1 until next node of front is null
            front=front.next
            back=back.next
        
        back.next=back.next.next # Remove target and link back node with next node of target
        
        return dummy.next
  • Time complexity : O(N)O(N)

profile
남들보단 느리지만, 끝을 향해

0개의 댓글