Collection of Data Elements along with the address to their consecutive element is called a Linked List. For Insertion in Beginning in A Linked List in JAVA We’ll first have to store the address to the previous first element along with the new element that will be inserted into the list. And also the head will now point towards the address of the new element.
Implementation
To insert a node in the beggining of a linked list, we first have to check the Head’s Reference to the first node of a linked list.
If the head is equal to null, then the list is already empty else the list already has an element whose reference is stored by the head.
To insert an element, in the beginning, we will have to replace the address stored by the head with the address of the new element we wish to insert.
The address space of the previously stored element will now be stored in the pointer reference of the inserted element.
import java.lang.*;
// Node Class
class Node {
int data;
Node next;
Node(int x)
{
data = x;
next = null;
}
}
class Main
{
static Node insertStart(Node head, int data)
{
// Creating newNode memory & assigning data value
Node newNode = new Node(data);
// assigning this newNode's next as current head node
newNode.next = head;
// re-assigning head to this newNode
head = newNode;
System.out.println(" inserted "+newNode.data);
return head;
}
static void display(Node node) {
System.out.println();
//as linked list will end when Node is Null
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
public static void main(String args[])
{
Node head = null;
head = insertStart(head,5);
head = insertStart(head,4);
head = insertStart(head,3);
head = insertStart(head,2);
head = insertStart(head,1);
display(head);
}
}
Login/Signup to comment