I'm trying to insert data before another data in a linked list but when I insert data after specific data . Instead of inserted before it. It's going to insert after that specific data. Here is my code, need correction, and Thanks in advance.
public void InsertBefore(int key, int element) {
Node current = head;
Node prev = null;
if (head != null) {
while (current != null) {
if (current.equals(key)) {
Node n = new Node(element);
n.next = current;
if (prev != null) {
prev.next = n;
}
return;
}
prev = current;
current = current.next;
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…