for deletion of a node at any index ,i'm not able to understand last line of code " temp.next = t;"

user8917095 :

`static class Node { E data; Node next;

    public Node(E data) {
        this.data = data;
        next = null;
    }
}
        public void deleteAtIndex(int index){     
        Node temp = head;
        for (int i = 1; i < index-1 ; i++) {
            temp=temp.next;
        }
        Node t = temp.next.next;
        temp.next = t;
       }`  

whats the need of writing that code in java ,because it was mentioned we use " temp.next = t;" to "Unlink the deleted node from list" .if if remove last line ,code is not giving required output.

RR_IL :

Let me give you an example -

Consider 5->6->10->15. Let's say you want to remove 10.

Logically you want to find 6 and make it point to 15.

First step to do so will require you to to get the node that points to your object (The one we want to remove)

 for (int i = 1; i < index-1 ; i++) {
            temp=temp.next;
 }

In this for loop we simply locate the node which points to the object we want to remove.


    Node t = temp.next.next;   //15
    temp.next = t; // Point 6 to 15

We set the next node of "6" to be the next node of the object we want to remove. Why? Because we want it to be: 5->6->15

Your t param holds the node with the value of "15".

Temp is "6".

Temp.next before the change pointed to 10. After the change it will point to 15.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=403526&siteId=1