I am implementing a single linked list of integer and I was wondering what is the most efficient way to locate a given value and remove it from the list. This is what I have so far:
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;
}
I am adding snippet here to remove the node from SinglyLinkedList. I prefer forLoop over while; that's the reason I have added snippet with for loop.
Hope the comment in the code helps you to navigate/dry run the snippet.
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;
}
Adding with while variant as well; just to go with your flow.
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;
}
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.