Skip to content

Commit bb0c19e

Browse files
authoredOct 16, 2022
Create linked_list_insertion.cpp
This Algorithm has all the operations that can be performed on a linked list
1 parent 65884fb commit bb0c19e

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed
 

‎linked_list_insertion.cpp

+103
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
#include<iostream>
2+
using namespace std;
3+
class node{
4+
public:
5+
int data;
6+
node* next;
7+
node(int val){
8+
data=val;
9+
next=NULL;
10+
}
11+
};
12+
void insertAtTail(node* &head,int val){
13+
node *n=new node(val);
14+
if(head==NULL){
15+
head=n;
16+
return;
17+
}
18+
node*temp=head;
19+
while(temp->next!=NULL){
20+
temp=temp->next;
21+
}
22+
temp->next=n;
23+
}
24+
void insertAtHead(node* &head,int val){
25+
node *n=new node(val);
26+
n->next=head;
27+
head=n;
28+
}
29+
bool search(node *head,int key){
30+
node *temp=head;
31+
while(temp!=NULL){
32+
if(temp->data==key){
33+
return true;
34+
}
35+
temp=temp->next;
36+
}
37+
return false;
38+
}
39+
void deleteAtHead(node* &head){
40+
node *todelete=head;
41+
head=head->next;
42+
delete todelete;
43+
}
44+
void deletion(node* &head,int val){
45+
if(head==NULL){
46+
return;
47+
}
48+
if(head->next==NULL){
49+
deleteAtHead(head);
50+
}
51+
node *temp=head;
52+
while(temp->next->data!=val){
53+
temp=temp->next;
54+
}
55+
node *todelete=temp->next;
56+
temp->next=temp->next->next;
57+
delete todelete;
58+
}
59+
node *reverse(node* &head){
60+
node *prevptr=NULL;
61+
node *currptr=head;
62+
node * nextptr;
63+
while(currptr!=NULL){
64+
nextptr=currptr->next;
65+
currptr->next=prevptr;
66+
prevptr=currptr;
67+
currptr=nextptr;
68+
}
69+
return prevptr;
70+
}
71+
node * reverseRecursive(node* &head){
72+
if(head==NULL ||head->next==NULL){
73+
return head;
74+
}
75+
node *newHead=reverseRecursive(head->next);
76+
head->next->next=head;
77+
head->next=NULL;
78+
return newHead;
79+
}
80+
void display(node*head){
81+
node *temp=head;
82+
while(temp!=NULL){
83+
cout<<temp->data<<"->";
84+
temp=temp->next;
85+
}cout<<"NULL"<<endl;
86+
}
87+
int main(){
88+
node *head=NULL;
89+
insertAtTail(head,1);
90+
insertAtTail(head,2);
91+
insertAtTail(head,3);
92+
insertAtTail(head,4);
93+
display(head);
94+
insertAtHead(head,0);
95+
display(head);
96+
cout<<endl;
97+
cout<<search(head,2)<<endl;
98+
deletion(head,2);
99+
display(head);
100+
node * newhead=reverseRecursive(head);
101+
display(newhead);
102+
return 0;
103+
}

0 commit comments

Comments
 (0)
Please sign in to comment.