adplus-dvertising
Coders Packet

Insertion in a Linked List using C++

By Raunak Chhabra

In this we will see how to insert data in linked list in C++, from last node to the first node.

#include
using namespace std;

class Node{
public:
       int data;
       Node*next;

       Node(int d){
           data = d;
           next = NULL;
       } 
};


void insertAtHead(Node*&head, int d){
    if(head==NULL){
        head = new Node(d);
        return;
    }
    Node*n = new Node(d);
    n->next = head;
    head = n;
}
void print(Node*head){
    while(head!=NULL){
        cout<data<<"->";
        head = head->next;
    }
}
int main(){
    Node*head = NULL;
    insertAtHead(head,3);
    insertAtHead(head,2);
    insertAtHead(head,1);
    insertAtHead(head,0);
    print(head);
}

 

#include
using namespace std;
class Node{
public:
int data;
Node*next;
 
Node(int d){
data = d;
next = NULL;
}
};
 
Starting of with including the main C++ header file. We initiated by making a class name Node and setting that we are going to have 2 elements in, the data and node*next which would basically consist of the address to the next node. Since it would point to yet another whole node so it's been named node*. After that we have Node(int d) this is basically initializing the constructor. Always remember that, the name of class and constructor is always same.
 
void insertAtHead(Node*&head, int d){
if(head==NULL){
head = new Node(d);
return;
}
Node*n = new Node(d);
n->next = head;
head = n;
}
void print(Node*head){
while(head!=NULL){
cout<data<<"->";
head = head->next;
}
}
int main(){
Node*head = NULL;
insertAtHead(head,3);
insertAtHead(head,2);
insertAtHead(head,1);
insertAtHead(head,0);
print(head);
}
 
Now we created an insert at head function which would take the reference to head and data and correspondingly insert the data as well. And if incase the head is empty it will create a new node and insert the data. Then we have created a print function as well. And ofcourse then the main function and calling the print method to print the data inserted in the linked list as well.

 

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Raunak Chhabra (raunakchhabra)

Download packets of source code on Coders Packet