Given the head of a linked list, remove the nth node from the end of the list and return its head.
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]
# 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]:
dummy = ListNode(0,head) # insert dummy as first null node
left = dummy # left starts at dummy
right = head # expand right until n distance from left
while n > 0 and right: # expand until right is at end of list
right = right.next
n -= 1
while right: # when right is n distance from left check if right is at end
left = left.next
right = right.next
# delete when right is at end
left.next = left.next.next
return dummy.next

https://leetcode.com/problems/remove-nth-node-from-end-of-list/?envType=featured-list&envId=top-interview-questions?envType=featured-list&envId=top-interview-questions
'LEETCODE' 카테고리의 다른 글
#11. Container With Most Water [Two Ptr] (0) | 2023.10.12 |
---|---|
#7. Reverse Integer (0) | 2023.10.10 |
#5. Longest Palindromic Substring (even/odd ptrs) (0) | 2023.10.10 |
# 17. Letter Combinations of a Phone Number [BACKTRACK, DFS] (0) | 2023.10.08 |
#3. Longest Substring Without Repeating Characters [MEDIUM] (0) | 2023.10.07 |