Skip to content

Instantly share code, notes, and snippets.

@xnorcode
Created May 3, 2018 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xnorcode/bb2f91e3f462d2cf2c330b735deb5b90 to your computer and use it in GitHub Desktop.
Save xnorcode/bb2f91e3f462d2cf2c330b735deb5b90 to your computer and use it in GitHub Desktop.
Linked List Add Node After Another Node
public class LinkedList<T> {
// Reference to the head node
Node head;
public void addAfter(T data, T target){
// create new node
Node newNode = new Node(data, null);
// check if list empty
if(head == null){
// set new node to tail
head = newNode;
return;
}
// check head value
if(head.data == target){
// helper method below to add newNode
head = addAfter(head, newNode);
return;
}
// get head reference
Node current = head;
// iterate nodes
while(current.next != null){
// check node value
if(current.next.data == target){
// helper method below to add newNode
current.next = addAfter(current.next, newNode);
return;
}
// go to next node
current = current.next;
}
// Add to tail
current.next = newNode;
}
// helper method to add a node after another node
private Node addAfter(Node head, Node newNode){
// set newNodes next ref. to head's next ref
newNode.next = head.next;
// set head's next to be the newNode
head.next = newNode;
// return head
return head;
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment