Write a program in C++ to insert a Node at the beginning of the given Singly linked list

C++Server Side ProgrammingProgramming

A linked List is a linear data structure that has multiple nodes that are connected with each other. Each node consists of two fields Data Field and address of the next node.

Let us assume we have given a singly linked list the task is to insert a node at the beginning of the given linked list. For example,

Input-1 − 1 → 2 → 3 → 4

Insert ‘5’ at the head or beginning of the given linked list.

Output − 5 → 1 → 2 → 3 → 4

Explanation − After inserting the node at the beginning of the linked list it will print the linked list as 5 → 1 → 2 → 3 → 4.

Approach to solve this problem

Initially, we have given a linked list that consists of nodes. Each node contains the data and address to the next node.

Since we have already created a node thus we will create a function that will take the address of the head node as a parameter and the data which we have to insert at the beginning of the linked list and insert the data at the beginning. Now point the head to the newly inserted node.

  • A function insertAthead(node*&head, int data) takes the address of the head node and the data which we have to insert.

  • Create a new node and insert the data into it.

  • Move the head to the newly created node.

  • Print the linked list.

Example

#include<iostream>
using namespace std;
class node{
   public:
      int data;
      node*next;
      node(int d);
      data=d;
      next= NULL;
   }
};
void insertAthead(node*&head, int data){
   node*n= new node(data);
   n->next= head;
   head= n;
}
void print(node*head){
   while(head!=NULL){
      cout<<head->data<<"->";
      head= head->next;
   }
}
int main(){
   node*head= NULL;
   insertAthead(head,5);
   insertAthead(head,2);
   insertAthead(head,8);
   insertAthead(head,3);
   print(head);
}

Output

Running the above code will generate the output as,

3→ 8→ 2→ 5 →

Inserting the nodes 3, 8, 2, and 5 at the beginning of the linked list, it will generate the output as − 3→ 8→ 2→ 5 →.

raja
Published on 05-Feb-2021 07:56:04
Advertisements