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.

 

What is A Linked List?

 

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
// on linked list
class LinkedList
{
    Node head; // head of list

    /* Linked list Node*/
    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 */
        new_node.next = head;

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

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

    /* Driver program to test above function*/
    public static void main(String[] args)
    {
        /* Start with the empty list */
        LinkedList llist = new LinkedList();

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

        System.out.println("\nCreated Linked list is: ");
        llist.printList();
    }
}

 

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

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