Remove Nth Node From End of List
Question
None
Example 1
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Solution
- ▭
- ▯
all//Remove Nth Node From End of List.py
# 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, n):
dummy = ListNode(0)
dummy.next = head
first = dummy
second = dummy
for i in range(n + 1):
first = first.next
while first:
first = first.next
second = second.next
second.next = second.next.next
return dummy.next
all//Remove Nth Node From End of List.py
# 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, n):
dummy = ListNode(0)
dummy.next = head
first = dummy
second = dummy
for i in range(n + 1):
first = first.next
while first:
first = first.next
second = second.next
second.next = second.next.next
return dummy.next