Singly Linked List using java.

Singly Linked list using java

Singly Linked List is created for adding the elements one after another where each Node is linked to the other Node sequentially.
The operations covered in this post are
  •      Append to the end
  •      Add in the middle of linked list.

Append to the end

How we are going to create linked list in the java.
Create a custom class which Is having structure

Now when we Create a instance of linked.

There are conditions
  • The LinkedList is empty then assign as head to the newly created node.
  • If the Linked list !=empty then traverse till end and then assign next value of last Node with new node.
  • The LinkedList is empty then assign as head to the newly created node.

Now you might be wondering what is use of these below two lines.

Linked p;   this line means create a empty node which will act as a pointer for navigation.

 p=head;   this means we have copied head node in this p node that means we start traverse from head.
  • If the Linked list !=empty then traverse till end and then assign next value of last Node with new node.

How to insert item in the middle of linked list

 
We need to traverse till the specified location.

Once we have reached specified location.
Now copy the next location pointer of p node to the next location pointer of our newly created node.
 

And copy the reference of new node to the next location of the p node.

Here is the complete code.

For further studies please read

W3Schools

Leave a Reply

Your email address will not be published. Required fields are marked *