I've been trying to insert a node into a linked list after the current node using Java. I've been able to get the insertion before the current node but I cannot get this to work:
Here is the code for insertNodeBefore
. I just want to know if there is a way to adapt this to be able to insert after the current node?
// Insert new node nVal to the list before current node curVal
public void insertNodeBefore(E nVal, E curVal) {
Node<E> newNode = new Node<E>(nVal);
Node<E> curr = head;
Node<E> prev = null;
if (head.getNodeValue() == curVal) {
newNode.setNext(head);
head = newNode;
return;
}
// scan until locate node or come to end of list
while (curr != null) {
// have a match
if (curr.getNodeValue() == curVal) {
// insert node
newNode.setNext(curr);
prev.setNext(newNode);
break;
} else {
// advanced curr and prev
prev = curr;
curr = curr.getNext();
}
}
}
Basically find the node and then:
Something like this should work:
public void insertNodeBeAfter(E nVal, E curVal) {
Node<E> newNode = new Node<E>(nVal);
Node<E> curr = head;
// scan until locate node or come to end of list
while (curr != null) {
// have a match
// Replaced == with .equals
if (curr.getNodeValue().equals(curVal)) {
// insert node
newNode.setNext(curr.getNext());
curr.setNext(newNode);
break;
} else {
curr = curr.getNext();
}
}
}
Note is not necessary to have a different treatement for the head because it doesn't change.
Note: could be interesting to handle NOT silently if the list is empty or if the curVal
is not found, for example throwing a RuntimeException
.
I tried to separate traversal code and the insertion code, it is all taken from the supplied code in your question.
private void insert(Node<E> prev, Node<E> after, Node<E> newNode) {
newNode.setNext(after);
if (prev != null) {
prev.setNext(newNode);
} else {
head = newNode;
}
}
public Node<E> findPrevOf(E curVal) {
Node<E> curr = head;
Node<E> prev = null;
// scan until locate node or come to end of list
while (curr != null) {
// have a match
if (curr.getNodeValue() == curVal) {
return prev;
} else {
// advanced curr and prev
prev = curr;
curr = curr.getNext();
}
}
throw new Exception("throw an exception to indicate that value does not exist");
}
public void insertNodeAfter(E nVal, E curVal) {
Node<E> prev = findPrevOf(curVal);
Node<E> curr = null;
if (prev == null) {
curr = head;
} else {
curr = prev.getNext();
}
Node<E> newNode = new Node<E>(nVal);
insert(curr, (curr == null ? curr: curr.getNext()), newNode);
}
// Insert new node nVal to the list before current node curVal
public void insertNodeBefore(E nVal, E curVal) {
Node<E> prev = findPrevOf(curVal);
Node<E> newNode = new Node<E>(nVal);
insert(prev, (prev == null ? head : prev.getNext()), newNode);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With