Insertion a Linked List front and End point in c++

 Insertion a Linked List front and End point in cpp DSA.

It' s very simple code. we can easily understand the approach ............

#include <iostream>
using namespace std;

class Node
{
public:
    int val;
    Node *next;
};

void frontAdd(Node *&head, int d)
{
    Node *tmp = new Node();
    tmp->val = d;
    tmp->next = head;
    head = tmp;
}

void endAdd(Node *&head, int d)
{
    Node *curr = head;
    Node *tmp = new Node();
    if (head == NULL)
    {
        curr = tmp;
        return;
    }

    tmp->val = d;
    tmp->next = NULL;

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

void print(Node *head)
{
    cout << endl;
    while (head)
    {
        cout << head->val << " --> ";
        head = head->next;
    }
    cout << "NULL" << endl
         << endl;
}

int main()
{

    Node *head = NULL;
    Node *second = NULL;
    Node *third = NULL;
    head = new Node();
    second = new Node();
    third = new Node();

    head->val = 1;
    head->next = second;
    second->val = 2;
    second->next = third;
    third->val = 4;
    third->next = NULL;
    cout << "this Current list ";
    print(head);
    cout << "Add a element in Front the list ";
    frontAdd(head, 5);
    print(head);
    cout << "Add a value in End the list ";
    endAdd(head, 10);
    print(head);
}

Output resultant :--

this Current list 1 --> 2 --> 4 --> NULL Add a element in Front the list 5 --> 1 --> 2 --> 4 --> NULL Add a value in End the list 5 --> 1 --> 2 --> 4 --> 10 --> NULL

Post a Comment

0 Comments