Google Add

Search

Write a C++ Program to insert a node at head of a linked list


C++ Program to insert a node at head of a linked list


In my previous post, i explain what is the advantage of linked list over arrays. Why we prefer linked list. 

C Program to insert a node at the beginning/head of a linked list


//

#include <iostream>
#include<cstdio>
#include<cstdlib>

using namespace std;

struct Node
{
 int data;
 Node *next;
};
// Insert node at the beginning

Node* Insert(Node *head,int data)
{
  
    Node *temp=(Node*)malloc(sizeof(struct Node));
    temp->data = data;
    temp->next = head;
    
    head = temp;
    
    return head;

}

void Print(Node *head)
{
 Node *temp = head;
        
        // Traverse and print the value

 while(temp!= NULL){
              cout<<temp->data<<"\n";
              temp = temp->next;
         }
}


int main()
{
 
 Node *head = NULL;
 
        head = Insert(head,5);
        head = Insert(head,2);
        head = Insert(head,3);
 
 Print(head);
}

No comments:

Post a Comment