0 votes
337 views
in Data Structure And Algorithm by
How to remove Nth node from end of Linked List in java

1 Answer

0 votes
by (3.7k points)
See the following running example to remove Nth Node from End of Linked List:-

package com.ds.linkedlist;

public class Node<T> {

    private T data;
    private Node<T> next;
   
    public Node(){
        setData(null);
        setNext(null);
    }
   
    public Node(T data){
        setData(data);
        setNext(null);
    }
   
    public T getData(){
        return data;
    }
   
    public void setData(T data){
        this.data = data;
    }
   
    public Node<T> getNext(){
        return next;
    }
   
    public void setNext(Node<T> next){
        this.next = next;
    }
   
}

package com.ds.linkedlist;

import java.util.HashMap;

public class SingleLinkedList<T> {
    Node<T> head = null;
    //To remove node from nth position from last
    public void deleteNthFromLast(int Nth) {
        Node<T> currHead = head;
        Node<T> ahead = head;
        Node<T> oldNode = null;
        while(Nth-- > 0){
            if(ahead == null)
                return;
            ahead = ahead.getNext();
        }
        while(ahead != null){
            oldNode = currHead;
            currHead = currHead.getNext();
            ahead = ahead.getNext();
        }
        oldNode.setNext(currHead.getNext());
    }
    public void addFirst(T data){
        if(data == null){
            return;
        }
        if(head == null){
            head = new Node<T>(data);
        }else{
            Node<T> newNode = new Node<T>(data);
            newNode.setNext(head);
            head = newNode;
        }
    }
   
    public void getNodeData(){
        Node<T> tempNode = head;
        if(tempNode==null){
            return;
        }
        while(tempNode != null){
            System.out.print(tempNode.getData()+" ");
            tempNode = tempNode.getNext();
        }
    }
}

package com.ds.linkedlist;

public class LinkedListTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        SingleLinkedList<Integer> singleLinkedList = new SingleLinkedList<Integer>();
        singleLinkedList.addFirst(10);
        singleLinkedList.addFirst(20);
        singleLinkedList.addFirst(30);
        singleLinkedList.addFirst(30);
        singleLinkedList.addFirst(40);
        System.out.println("Node List:-");
        singleLinkedList.getNodeData();
        System.out.println("Remove 3rd node form end");
        singleLinkedList.deleteNthFromLast(3);
        singleLinkedList.getNodeData();
    }
}

Output:-
Node List:-
40 80 30 20 10
Remove 3rd node form end
40 80 20 10

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...