Java 删除单链表上节点的最有效方法?
我正在实现一个整数的单链表,我想知道找到给定值并将其从列表中删除的最有效方法是什么。这就是我到目前为止所做的:Java 删除单链表上节点的最有效方法?,java,singly-linked-list,Java,Singly Linked List,我正在实现一个整数的单链表,我想知道找到给定值并将其从列表中删除的最有效方法是什么。这就是我到目前为止所做的: public class LinkedList { Node head; public void insert(int value){ Node newNode = new Node(); newNode.data = value; newNode.next = null; if(head==null){ head = new
public class LinkedList {
Node head;
public void insert(int value){
Node newNode = new Node();
newNode.data = value;
newNode.next = null;
if(head==null){
head = newNode;
} else {
Node iterator = head;
while(iterator.next!=null){
iterator = iterator.next;
}
iterator.next = newNode;
}
}
public void display(LinkedList list){
Node iterator = head;
while (iterator!=null){
System.out.println(iterator.data);
iterator = iterator.next;
}
}
public void remove(LinkedList list, int value){
Node iterator = head;
while(iterator!=null){
if(iterator.next.data == value){
iterator.next = iterator.next.next;
} else{
iterator = iterator.next;
}
}
}
}
public class Node {
int data;
Node next;
}
我在这里添加代码片段以从SingleLinkedList中删除节点。我更喜欢forLoop而不是while;这就是我添加带有for循环的代码段的原因 希望代码中的注释能帮助您导航/试运行代码段
public boolean remove(int value){
Node oneBeforeValueNode;
// Using for to iterate through the SinglyLinkedList
// head → is the head of your SingleLinkedList
for (Node node = head; node != null; node = node.next) {
// Compare the value with current node
if (value.equals(node.data)) {
// if matches then unlink/remove that node from SinglyLinkedList
// if its a first node in SingleLinkedList
if(oneBeforeValueNode==null){
// Considering there exists next element else SLL will be empty
head = head.next;
} else {
// if there exists next element it SLL it will attach that element with previous one
oneBeforeValueNode.next = node.next;
}
return true;
}
// Storing previous node from current
// To use it once value is found to reference it to current.next(node.next)
oneBeforeValueNode = node;
}
return false;
}
添加while变量;只是为了随波逐流
public Node remove(Node head, int key) {
Node current = head;
Node previous = null;
while (current != null) {
if(current.data == key) {
if(current == head) {
head = head.next;
current = head;
} else {
previous.next = current.next;
current = current.next;
}
} else {
previous = current;
current = current.next;
}
}
return head;
}
将抛出NPE。可能您应该从参数中删除LinkedList列表,因为您不使用它。正确,我得到了NPE,我的代码有什么问题?
迭代器。next
可以为null,以及迭代器。next.next
。还有,什么是头?您的代码中没有定义它。我只是添加了所有内容,谢谢