[英]How can I implement append and deleteNode methods for a LinkedList implementation in Java?
I am improving my data structures skills. 我正在提高我的数据结构技能。 I am trying to implement a LinkedList from scratch.
我正在尝试从头开始实现LinkedList。 This is what I have done so far:
到目前为止,这是我所做的:
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;
}
}
The problem is I don't understand the deleteNode method. 问题是我不了解deleteNode方法。 I have found it in the book Cracking the Code interview.
我在《 Cracking the Code》采访中找到了它。 Could someone please clarify for me what is actually happening?
有人可以帮我澄清一下实际情况吗? The whole reference thing is getting me confused.
整个参考资料使我感到困惑。
The deleteNode
method seems to return the linked list. deleteNode
方法似乎返回链接列表。 Here's what it does: 这是它的作用:
d
), then we just return the list starting from the second element ( head.next
). d
匹配),那么我们仅从第二个元素( head.next
)开始返回列表。 There's nothing linking back to that first element, so the first element is gone. n.next
. n.next
做到这n.next
。 If its data matches d
, then this node should be removed. d
匹配,则应删除此节点。 So then let the list skip that element: Set n.next
to be n.next.next
(which is the element after it) rather than the element that matched d
. n.next
设置为n.next.next
(它后面的元素),而不是与d
匹配的元素。 Normally these kinds of methods tend to return the element that was removed. 通常,这些方法倾向于返回被删除的元素。 Instead, this seems to return the list itself, which is represented by its head.
相反,这似乎返回列表本身,该列表由其头部表示。 That's why the method keeps returning
head
. 这就是为什么该方法不断返回
head
的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.