Delete node?
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;
}
Comments
Leave a comment