Remove Nth Node from End of Linked List | Linked List Problem

4 years ago Lalit Bhagtani 0

Problem Statement

You have given a singly linked list and an integer value n, remove the nth node from the end of a given linked list.

Example 

Linked List

Input :- head = [5, 4, 10, 15, 1] , node = 4
Output :- [5, 10, 15, 1]
Input :- head = [5, 4, 10, 15, 1, 5, 6] , node = 3
Output :- [5, 4, 10, 15, 5, 6]

Solution

We will create two variables current and previous. First, move the current variable to nth + 1 node from the start of the linked list, then move the previous and current variable together till the current variable reaches the last node of a linked list. Now assign the next value of previous.next node to the previous.next variable.

Program

public class Main {

	public static void main(String[] args) {
		
		ListNode head = null;
		
		ListNode node = new ListNode(5);
		head = node;		
		node.next = new ListNode(4);
		node = node.next;		
		node.next = new ListNode(10);
		node = node.next;		
		node.next = new ListNode(15);
		node = node.next;		
		node.next = new ListNode(1);
		node = node.next;
		node.next = new ListNode(5);
		node = node.next;
		node.next = new ListNode(6);
		
		Main main = new Main();
		head = main.removeNthFromEnd(head, 3);
		
		ListNode listNode = head;
		while(listNode != null) {
			System.out.print(listNode.value + ", ");
			listNode = listNode.next;
		}
	}
	
	/* Solution */
	public ListNode removeNthFromEnd(ListNode head, int n) {
	     
        ListNode current = head;
        ListNode previous = head;
        ListNode newHead = head;
        
        while(current != null && n>0){
            current = current.next;
            n--;
        }
        
        if(current == null){
            newHead = previous.next;
        }else {
            while(current.next != null){
                current = current.next;
                previous = previous.next;
            }
            previous.next = previous.next.next;
        }
        return newHead;
    }
	
	/* Definition of Linked List Node */
	public static class ListNode {		
		int value;
		ListNode next;
		
		public ListNode(int value) {
			this.value = value;
		}		
	}
}

Result

5, 4, 10, 15, 5, 6,

That’s all for Remove Nth Node from End of Linked List in Java, If you liked it, please share your thoughts in a comments section and share it with others too.