Road To Code

Road To Code

Inserting a node at the end of a linked list

Yash Naravade's photo
Yash Naravade

Published on Oct 7, 2021

2 min read

Subscribe to our newsletter and never miss any upcoming articles

Listen to this article

In our previous article we learned how to insert a node at the beginning of a linked list. In this article we will see how we can insert a node at the end of the linked list.

Approach:

  1. Declare head pointer and make it as NULL.

  2. Create a new node with the given data. And make the new node => next as NULL. We have to do this because the new node is going to be the last node.

  3. If the head node is NULL (Empty Linked List), make the new node as the head.

  4. If the head node is not NULL, i.e Linked list already has some elements, find the last node. Make the last node => next as the new node.

Example:

If this linked list looks like: 5->10->15->NULL.

And if you want to insert 20,

after insertion at end it will look like: 5->10->15->20->NULL.

Code:

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

class Node{
    public:
    int data;
    Node *next;
    Node()
    {
        this->next = NULL;
    }
};

void traverseLinkedList(Node *node)
{
    while(node!=NULL)
    {
        cout<<node->data<<", ";
        node = node->next;
    }
}

void insertAtEnd(int data, Node * &head)
{
    Node *node = head;

    Node *newNode = new Node();
    newNode->data = data;

    while(node->next!=NULL)
    {
       node = node->next;
    }

    node->next = newNode;        
}

int main()
{
    Node *head = new Node();
    head->data = 5;

    Node *first = new Node();
    first->data = 10;

    Node *last = new Node();
    last->data = 15;

    head->next = first;
    first->next = last;

    cout<<"Before Insertion: ";
    traverseLinkedList(head);

    insertAtEnd(20, head);

    cout<<"\nAfter Insertion: ";
    traverseLinkedList(head);

    return 0;
}

Output:

Before Insertion: 5, 10, 15, 
After Insertion: 5, 10, 15, 20,

This is how you insert a node at the end of the linked list.

 
Share this