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

huangapple go评论84阅读模式
英文:

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

问题

static class Node<E> {
    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;
}

这段代码是用Java编写的。代码中的temp.next = t;用于“从链表中断开已删除的节点”。如果删除掉最后一行,代码将无法得到所需的输出。

英文:

`static class Node<E> {
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 &lt; 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.

答案1

得分: 3

让我给你举个例子 -

考虑 5->6->10->15。
假设你想要移除 10。

从逻辑上讲,你想要找到 6 并使其指向 15。

第一步是这样做,需要你获取指向你要移除的对象的节点(我们想要移除的那个)。

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

在这个循环中,我们简单地定位指向我们要移除的对象的节点。


    Node t = temp.next.next;   //15
    temp.next = t; // 将 6 指向 15

我们将“6”的下一个节点设置为我们要移除的对象的下一个节点。
为什么呢?
因为我们希望它变成:
5->6->15

你的 t 参数保存着值为“15”的节点。

Temp 是“6”。

在更改之前,Temp.next 指向 10。更改后,它将指向 15。

英文:

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 &lt; 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.

答案2

得分: 0

使用temp.next = next,您正在更新对下一个节点的引用,从而删除了旧节点。您还可以在LinkedList的实现中看到这一点:#unlink(Node)

英文:

With temp.next = next you are updating the reference to the next node having deleted the old one. You can also see that in the LinkedList implementation: #unlink(Node)

huangapple
  • 本文由 发表于 2020年4月4日 15:31:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/61025045.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定