Insert A Node At Front In Linked List using C++

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 C++.

 

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.

 

 

Also Read: Print Cube Root Of A Number in C++

 

C++ Program To Insert A Node At Front In Linked List

 

Input:

 

push(&head,6)

 

Output:

 

Created Linked List is: 6

 

// C++ program to demonstrate
// insertion method on Linked List

#include <bits/stdc++.h>
using namespace std;

// A linked list node
class Node
{
    public:
    int data;
    Node *next;
};

/* insert a new node on the front of the list. */
void push(Node** head_ref, int new_data)
{
    /* 1. allocate node */
    Node* new_node = new Node();

    /* 2. put in the data */
    new_node->data = new_data;

    /* 3. Make next of new node as head */
    new_node->next = (*head_ref);

    /* 4. move the head to point to the new node */
    (*head_ref) = new_node;
}


// This function prints contents of
// linked list starting from head
void printList(Node *node)
{
    while (node != NULL)
    {
        cout<<" "<<node->data;
        node = node->next;
    }
}

/* Driver code*/
int main()
{
    /* Start with the empty list */
    Node* head = NULL;
    
    // Insert 6. So linked list becomes 6->NULL
    push(&head, 6);
    
    cout<<"Created Linked list is: ";
    printList(head);
    
    return 0;
}

 

 

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.