Insert A Node At Front In Linked List using Java

Technology and generation are growing up together, and the younger generation users are somewhat connected with tech and the internet all the time. Not to mention, today the whole world in this time of crisis is working over the internet. But to make these technologies, software, etc a software developer must have excellent problem-solving skills. In this world where the internet is the new fuel, one needs to be pretty sharp. And by sharp, for software developers, it means knowing how to automate real-world problems using computer programs. Data structures help a lot in this journey of logic building. So today we’re going to write a simple data structure program to Insert A Node At the Front In Linked List using Java.

A linked list is a basic list of nodes containing different elements for all algorithms in data structures. Also, it’s pretty easy to understand.

What’s The Approach?

• Firstly we’ll allocate a new node, by simply creating it.

• Next up we’ll insert the data in the linked list.

• Now, this new node is going to become the head of the linked list.

• At the last, the head is going to point towards the New Node.

Also Read: Print Cube Root Of A Number in Java

Java Program To Insert A Node At Front In Linked List

Input:

`push(6)`

Output:

`Created Linked List is: 6`

```// Java program to demonstrate insertion
{

class Node
{
int data;
Node next;
Node(int d) {data = d; next = null; }
}

/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
/* 1 & 2: Allocate the Node &
Put in the data*/
Node new_node = new Node(new_data);

/* 3. Make next of new Node as head */

/* 4. Move the head to point to new Node */
}

/* This function prints contents of linked list starting from
the given node */
public void printList()
{
while (tnode != null)
{
System.out.print(tnode.data+" ");
tnode = tnode.next;
}
}

/* Driver program to test above function*/
public static void main(String[] args)
{

// Insert 6. So linked list becomes 6->NUllist
llist.push(6);