Delete node
#include <bits/stdc++.h>
using namespace std;
class Node{
public:
int d;
Node* nxt;
};
void insert(Node** head_r, int new_d)
{
Node* new_n = new Node();
new_n->d = new_d;
new_n->nxt = (*head_r);
(*head_r) = new_n;
}
void delete(Node** head_r, int k)
{
Node* temp = *head_r;
Node* prev = NULL;
if (temp != NULL && temp->d == k)
{
*head_r = temp->nxt;
delete temp;
return;
}
else
{
while (temp != NULL && temp->d != k)
{
prev = temp;
temp = temp->nxt;
}
if (temp == NULL)
return;
prev->nxt = temp->nxt;
delete temp;
}
}
void display(Node* n)
{
while (n != NULL)
{
cout << n->d << " ";
n = n->nxt;
}
}
int main()
{
Node* h = NULL;
insert(&h, 10);
insert(&h, 11);
insert(&h, 12);
puts("Before deletion: ");
display(h);
delete(&h, 12);
puts("\nAfter deletion: ");
display(h);
return 0;
}
Comments
Leave a comment