[英]How can I implement append and deleteNode methods for a LinkedList implementation in Java?
我正在提高我的数据结构技能。 我正在尝试从头开始实现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》采访中找到了它。 有人可以帮我澄清一下实际情况吗? 整个参考资料使我感到困惑。
deleteNode
方法似乎返回链接列表。 这是它的作用:
d
匹配),那么我们仅从第二个元素( head.next
)开始返回列表。 没有链接回第一个元素的内容,因此第一个元素不见了。 正是我们想要的。 n.next
做到这n.next
。 如果其数据与d
匹配,则应删除此节点。 因此,让列表跳过该元素:将n.next
设置为n.next.next
(它后面的元素),而不是与d
匹配的元素。 通常,这些方法倾向于返回被删除的元素。 相反,这似乎返回列表本身,该列表由其头部表示。 这就是为什么该方法不断返回head
的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.