Remove Nth Node From End Of The List Program Solution

REMOVE Nth NODE FROM END OF LIST Program Solution in C++, JAVA, Python | Leetcode Program Solution

We at gradjobopenings.com provide free job alerts of freshers job drives. In this website we list on campus job openings for freshers and off campus job openings for freshers and also work from home job openings. This is the best website to apply for off campus drive in India. Visit our website for government job alerts and private job alerts. We also list free interview notes and study materials, one of the best interview study website.comfortable to face the interviews:

Problem Statement:

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

Follow up: Could you do this in one pass?

  • Time: O(n)O(n)
  • Space: O(1)O(1)

Remove Nth Node From End Of The List Program Solution In C++

class Solution {
 public:
  ListNode* removeNthFromEnd(ListNode* head, int n) {
    auto slow = head;
    auto fast = head;

    while (n--)
      fast = fast->next;
    if (!fast)
      return head->next;

    while (fast->next) {
      slow = slow->next;
      fast = fast->next;
    }
    slow->next = slow->next->next;

    return head;
  }
};

Remove Nth Node From End Of The List Program Solution In JAVA

class Solution {
  public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode slow = head;
    ListNode fast = head;

    while (n-- > 0)
      fast = fast.next;
    if (fast == null)
      return head.next;

    while (fast.next != null) {
      slow = slow.next;
      fast = fast.next;
    }
    slow.next = slow.next.next;

    return head;
  }
}

Remove Nth Node From End Of The List Program Solution In PYTHON

class Solution:
  def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
    slow = head
    fast = head

    for _ in range(n):
      fast = fast.next
    if not fast:
      return head.next

    while fast.next:
      slow = slow.next
      fast = fast.next
    slow.next = slow.next.next

    return head
MORE PROGRAMS & SOLUTION : CLICK HERE
LATEST JOB OPENINGS: CLICK HERE
INTERVIEW NOTES & STUDY MATERIALS: CLICK HERE

Leave a Comment

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

error: Content is protected !!