Answer to Question #273344 in C++ for Korea

Question #273344

Delete node?




1
Expert's answer
2021-12-01T00:52:36-0500


SOLUTION


In this solution we will write a C++ code to delete a node of a linked list

In order to delete a node of a linked list, we connect the predecessor node of the node to be deleted by the successor node of the same node. Lets take an example we have

a linked list K → L → M, then to delete the node ‘L’, we will connect ‘K’ to ‘M’ i.e., K → M.


SOLUTION CODE


#include <iostream>


using namespace std;


struct node
{
    int data;
    node *next;
};


class linked_list
{
private:
    node *head,*tail;
public:
    linked_list()
    {
        head = NULL;
        tail = NULL;
    }


    void add_node(int n)
    {
        node *temp = new node;
        temp->data = n;
        temp->next = NULL;


        if(head == NULL)
        {
            head = temp;
            tail = temp;
        }
        else
        {
            tail->next = temp;
            tail = tail->next;
        }
    }


    node* get_head_function()
    {
        return head;
    }


    static void display_function(node *head)
    {
        if(head == NULL)
        {
            cout << "NULL" << endl;
        }
        else
        {
            cout << head->data << endl;
            display_function(head->next);
        }
    }


    static void concatenate_function(node *a,node *b)
    {
        if( a != NULL && b!= NULL )
        {
            if (a->next == NULL)
                a->next = b;
            else
                concatenate_function(a->next,b);
        }
        else
        {
            cout << "Either a or b is NULL\n";
        }
    }


    void front(int n)
    {
        node *temp = new node;
        temp -> data = n;
        temp -> next = head;
        head = temp;
    }


    void after(node *a, int value)
    {
        node* p = new node;
        p->data = value;
        p->next = a->next;
        a->next = p;
    }
};


int main()
{
    linked_list a;
    a.add_node(1);
    a.add_node(2);
    a.front(3);
    a.display_function(a.get_head_function());
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS