Given the head
of a linked list, remove the 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:
sz
.1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
# 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