I'm having a problem deleting nodes from singly linked lists in Java. I have a list, which has data of integers, and I need to delete all nodes, whose value can be divided by divided by four. I also need to move the head and tail pointers in case either of the head or tail elements are deleted. I wrote method for this, and most of the time it works just like I need it to, but sometimes it throws NullPointerException. How can I fix it? Here's my code:
public void delete(){
Node temp = head, prev = null;
if (temp != null && temp.data % 4 == 0)
{
head = temp.next;
temp = head;
}
while (temp.next != null)
{
if (temp.data % 4 != 0) {
prev = temp;
temp = temp.next;
}
else {
prev.next = temp.next;
temp = prev.next;
}
}
if (tail.data % 4 == 0) {
tail = prev;
tail.next = null;
}
}
while (temp.next != null)
: temp may be null. And some more small problems.
This is due to too much complexity.
public void delete() {
Node prev = null;
for (Node temp = head; temp != null; temp = temp.next) {
if (temp.data % 4 == 0) {
if (prev == null) {
head = temp.next;
} else {
prev.next = temp.next;
}
} else {
prev = temp;
}
}
tail = prev;
}
prev
to the valid previous node.tail
is updated to the last element. in your while condition add one more null check:
while (null.= temp && null != temp.next)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.