linked list imp and rep , traversing, searching , insertion and deletion
#include<iostream>
using namespace std;
// searching and traversing in linked list
class node{
public:
int data;
node* next;
node(int val){
data=val;
next=NULL;
}
};
// void deleteAtHead(node* &head, int val){
// node* n=new node(val);
// n->next=head;
// head=n;
// }
// void insertElement(node* &head, int val){
// }
void deleteAtHead(node* &head){
node* todelete=head;
head=head->next;
delete todelete;
}
void deleteElement(node* &head, int val){
if(head==NULL){
return;
}
node* temp=head;
if(head->next==NULL){
deleteAtHead(head);
return;
}
while(temp->next->data!=val){
temp=temp->next;
}
node* todelete=temp->next;
temp->next=temp->next->next;
delete todelete;
}
void insertElement(node* &head, int val,int prev_value){
node* n=new node(val);
node *temp=head;
if(head==NULL){
head=n;
return;
}
// node* temp=head;
while(temp->data!=prev_value){
temp=temp->next;
}
node* temp1=temp->next;
temp->next=n;
n->next=temp1;
}
void insertAtTail(node* &head, int val){
node* n=new node(val);
if(head==NULL){
head=n;
return;
}
node* temp=head;
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=n;
}
void display(node* head){
node* temp=head;
while(temp!=NULL){
cout<<temp->data<<"->";
temp=temp->next;
}
cout<<"NULL"<<endl;
}
bool search(node* &head, int key){
node* temp=head;
while(temp!=NULL){
if(temp->data==key){
return true;
}
temp=temp->next;
}
return false;
}
int main(){
node* head=NULL;
insertAtTail(head, 1);
insertAtTail(head, 2);
insertAtTail(head, 3);
insertAtTail(head, 4);
display(head);
cout<<search(head, 3)<<endl;
deleteElement(head, 2);
display(head);
insertElement(head, 8,3);
display(head);
return 0;
}
// output
1->2->3->4->NULL
1
1->3->4->NULL
1->3->8->4->NULL
Comments
Post a Comment