Leetcode 19: Remove Nth Node From End of List

19. Remove Nth Node From End of List 

  • Total Accepted: 140954
  • Total Submissions: 445848
  • Difficulty: Easy
  • Contributors: Admin

Given a linked list, remove the nth node from the end of list and return its head.

For example,

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

   After removing the second node from the end, the linked list becomes 1->2->3->5.

Note:
Given n will always be valid.
Try to do this in one pass.

 

Code

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        i = 0
        head_bak, n_to_last, n_plus_1_to_last = head, head, head
        
        while head:
            i += 1
            if i >= n+1:
                n_to_last = n_to_last.next
            if i >= n+2:
                n_plus_1_to_last = n_plus_1_to_last.next
            head = head.next
        
        if i == n:
            return head_bak.next
        else:
            n_plus_1_to_last.next = n_to_last.next
            return head_bak
        

 

Idea

Maintain two pointers. One is pointing to (n+1) to the last element. The other is point to n to the last element. Be careful for the corner case when there are only n elements in total.

Another idea can be seen: https://discuss.leetcode.com/topic/7031/simple-java-solution-in-one-pass

Leave a comment

Your email address will not be published. Required fields are marked *