Linked List Inserting & Deleting a node in C++ in DSA

 Linked List Inserting & Deleting a node in C++ in DSA

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node *next;
};

void insert(node ** head, int new_data){
node * temp =new node();
temp->data=new_data;
temp->next=(*head);
*head=temp;
}
void display(node *n){
while(n!=NULL){
cout<<n->data<<" ->"<<" ";
n=n->next;
}
cout<<"NULL"<<endl;
}
void del_node(node** head, int key){
cout<<"The deleted node is "<<key<<endl;
node* temp=*head;
node *prev=NULL;
if(temp!=NULL && temp->data==key){
*head=temp->next;
delete temp;
return ;
}
else{
while(temp!=NULL && temp->data!=key){
prev=temp;
temp=temp->next;
}
if(temp==NULL){
return;
}
prev->next=temp->next;
delete temp;
}
}
int main() {
node * head=NULL;
cout<<"The Insert Beginning Element "<<endl;
insert(&head,1);
insert(&head,2);
insert(&head,3);
insert(&head,5);
insert(&head,4);
display(head);
del_node(&head,2);
display(head);
return 0;
}

Post a Comment

0 Comments