Created
May 3, 2018 16:38
-
-
Save xnorcode/bb2f91e3f462d2cf2c330b735deb5b90 to your computer and use it in GitHub Desktop.
Linked List Add Node After Another Node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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