我正在提高我的数据结构技能。我试图从头开始实现LinkedList。 这是我到目前为止所做的:
class Node {
Node next = null; //reference to null
Object data; //value of the node
public Node(Object d) {
data = d; //constructor that assigns the node's value to the node
}
void append(Object d) {
Node end = new Node(d); //create the new node
Node n = this;
while (n.next != null) { //keep moving the reference until we reach null which is the reference of the last node
n = n.next;
}
n.next = end; //Assign the null reference to the node end which is the node to be added
}
Node deleteNode(Node head, Object d){
Node n = head; //Call the pointer to the head n;
if (n.data == d) { //Check if the data of the current node is same as node to be deleted
return head.next; //Here I got lost, I don't know why we're returning head.next
}
while (n.next != null) { //as long as we have reached the last node
if (n.next.data == d) {
n.next = n.next.next; //I don't get this
return head; //Why are we returning head
}
n = n.next;
}
return head;
}
}
问题是我不了解deleteNode方法。我在“Cracking the Code”一书的采访中找到了它。请问有人请告诉我实际发生了什么?整个参考事情让我感到困惑。
答案 0 :(得分:0)
deleteNode
方法似乎返回链表。这是它的作用:
d
匹配),那么我们只从第二个元素(head.next
)开始返回列表。没有任何东西链接回第一个元素,所以第一个元素消失了。正是我们想要的。n.next
来做到这一点。如果其数据与d
匹配,则应删除此节点。那么让列表跳过该元素:将n.next
设置为n.next.next
(后面的元素),而不是匹配d
的元素。通常这些方法往往会返回被删除的元素。相反,这似乎返回列表本身,由其头部表示。这就是该方法不断返回head
。