Skip to content

Instantly share code, notes, and snippets.

@prasath95
Created May 8, 2022 08:37
Show Gist options
  • Save prasath95/e6a9503fa6013e1d09aefb347003145b to your computer and use it in GitHub Desktop.
Save prasath95/e6a9503fa6013e1d09aefb347003145b to your computer and use it in GitHub Desktop.
public class LinkedList {
Node headNode;
/*
* insert
* */
public void insert(int value){
Node newNode=new Node();
newNode.value=value;
/*
* if we insert the value that will be the end of the linkedList
* that's why next node is null in the single linkedList
* */
newNode.nextNode=null;
/*
* headNode!=null means, it's already created
* */
if(headNode!=null){
/*
* 1. assign the headNode(First Node) to a Node Reference(here n is the object reference)
* 2. then run the while loop until get the nextNode becomes null
* --> if it's becomes null, that's the before last node,
* 3. then nextNode must be null, because it's a last element
* 4. then assign the created above newNode as the nextNode for the last available node- n.nextNode=newNode;
* */
//1
Node n=headNode;
//2
while (n.nextNode!=null){
n=n.nextNode;
}
//3
n.nextNode=newNode;
/*
* if the headNode is null which is means that's the new Node in the LinkedList
* */
}else {
headNode=newNode;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment