Delete the nth last node of the linked list

Given a linked list, delete the nth last node of the list and return the head node of the list.

Example:

Given a list: 1 - > 2 - > 3 - > 4 - > 5, and n = 2

When the penultimate node is deleted, the list changes to 1 - > 2 - > 3 - > 5
Explain:

The given n guarantee is valid.

Advance:

Can you try a scan implementation?

Analysis

Solution 1

  1. Store the numbers in the linked list into a list in order
  2. Find the index of the node to delete
  3. Traverse to the node to delete
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        
        if head == None:
            return None
        
        # l number stored in the linked list in order
        l = []
        
        cur = head
        
        while cur is not None:
            l.append(cur.val)
            cur = cur.next
        
        if n == len(l):
            return head.next
        
        # num represents cur's current index
        num = 0
        cur = head
        # pre points to the previous node of cur
        pre = None
        
        # m indicates the index of the node to be deleted
        m = len(l) - n
        
        # cur points to the node to delete
        while num < m:
            num += 1
            pre = cur
            cur = cur.next
           
        pre.next = cur.next
        return head
        

Solution 2

  1. Double pointer p q points to the head node
  2. One pointer first moves N positions backward so that the distance between the two pointers is N
  3. Move two pointers at the same time until the latter pointer moves to the tail, so that the former pointer points to the previous node of the nth last node
  4. Note that in special cases, if q already points to None, the node to be deleted is the head node
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        
        if head == None:
            return None
        
        p = head
        q = head
        q_num = 0
        
        while q_num < n:
            q = q.next
            q_num += 1
        
        if q is None:
            return head.next
        
        while q.next is not None:
            p = p.next
            q = q.next
            
        p.next = p.next.next
        return head

Posted by k3Bobos on Sat, 23 Nov 2019 10:15:51 -0800