Remove the nth node from the end of a linked list

By   Tewodros   Date Posted: Oct. 10, 2023  Hits: 338   Category:  Algorithm   Total Comment: 0             A+ A-


side

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

Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]

Solution:


We count the size of the linked list.

To find them nth node from the end we just need to subtract n from count. That is the trick! 


 

public class Solution {

    public ListNode RemoveNthFromEnd(ListNode head, int n) {

        ListNode i = head;

        int count = 0;

        while(i!=null)

        {

            i=i.next;

            count++;

        }

        

        int m = count-n;

        ListNode it = head;

        int j=0;

        while(j<m-1)

        {

            it=it.next;

            j++;

        }

        

        if(count==n)

        {            

            return head.next;

        }

        

        if(it.next!=null )

          it.next = it.next.next;

        

        if(count==1 && n==1) return null;

        return head;

    }

}


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* nhibuv

Back to Top