Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions Linked list Deletion.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
#include<iostream>
using namespace std;

class node{
public:
int data;
node *next;

node(int d){
data =d;
next=NULL;
}
};
//insert at beginning
void insert_at_head(node *&head,int data){
if(head==NULL){
head=new node(data);
return;
}
node *n=new node(data);
n->next=head;
head=n;
}
//insert at last
void insert_at_tail(node *&head,int data){
if(head==NULL){
head=new node(data);
return;
}
node *tail=head;
while(tail->next!=NULL){
tail=tail->next;
}
tail->next=new node(data);
return;
}
//length of linked list
int length(node *head){
int cnt=0;
while(head!=NULL){
cnt++;
head=head->next;
}
return cnt;
}
//insert at given position
void insert_in_middle(node *&head,int data,int p){
//corner case
if(head==NULL or p==0){
insert_at_head(head,data);
}
else if(p>length(head)){
insert_at_tail(head,data);

}
else{
//take p-1 jumps
int jump=1;
node *temp=head;
while(jump<=p-1){
temp=temp->next;
jump++;
}
//create a new node
node *n =new node(data);
n->next=temp->next;
temp->next=n;
}
}
//display the list
void print(node *head){
while(head!=NULL){
cout<<head->data;
head=head->next;
}
}
//delete from the head
void delete_from_head(node *&head){
if(head==NULL){
return;
}
node *temp=head->next;
delete head;
head=temp;
}

int main(){
node *head=NULL;
insert_at_head(head,5);
insert_at_head(head,4);
insert_at_head(head,2);
insert_at_head(head,1);
insert_at_head(head,0);
print(head);
cout<<endl;

insert_at_tail(head,6);
insert_in_middle(head,3,3);

print(head);
cout<<endl;

delete_from_head(head);
print(head);

}