In this post, we are going to solve the 19. Remove Nth Node From End of List problem of Leetcode. This problem 19. Remove Nth Node From End of List is a Leetcode medium level problem. Let’s see the code, 19. Remove Nth Node From End of List – Leetcode Solution.
Problem
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]
Constraints
- The number of nodes in the list is
sz
. 1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
Now, let’s see the code of 19. Remove Nth Node From End of List – Leetcode Solution.
Remove Nth Node From End of List – Leetcode Solution
19. Remove Nth Node From End of List – Solution in Java
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode slow = head; ListNode fast = head; while(n-- > 0) fast = fast.next; if(fast == null){ ListNode rn = head; head = head.next; rn = null; return head; } while(fast.next != null){ slow = slow.next; fast = fast.next; } ListNode rn = slow.next; slow.next = rn.next; rn = null; return head; } }
19. Remove Nth Node From End of List – Solution in C++
ListNode *removeNthFromEnd(ListNode *head, int n) { if (!head) return nullptr; ListNode new_head(-1); new_head.next = head; ListNode *slow = &new_head, *fast = &new_head; for (int i = 0; i < n; i++) fast = fast->next; while (fast->next) { fast = fast->next; slow = slow->next; } ListNode *to_de_deleted = slow->next; slow->next = slow->next->next; delete to_be_deleted; return new_head.next; }
19. Remove Nth Node From End of List – Solution in Python
def removeNthFromEnd(self, head, n): fast = slow = dummy = ListNode(0) dummy.next = head for _ in xrange(n): fast = fast.next while fast and fast.next: fast = fast.next slow = slow.next slow.next = slow.next.next return dummy.next
Note: This problem 19. Remove Nth Node From End of List is generated by Leetcode but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.