-
Notifications
You must be signed in to change notification settings - Fork 54
/
insertion and deletion in linked list using recursion.cpp
127 lines (95 loc) · 1.64 KB
/
insertion and deletion in linked list using recursion.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include<iostream>
using namespace std;
class Node{
public :
int data;
Node *next;
Node(int data)
{
this -> data = data;
next = NULL;
}
};
Node *take_input2()
{
int data;
cin>> data;
Node *head = NULL;
Node *tail = NULL;
while(data != -1)
{
Node *newNode = new Node(data);
if(head == NULL)
{
head = newNode;
tail = newNode; //time complexity is O(n)
}
else
{
tail -> next = newNode;
tail = newNode;
}
cin>>data;
}
return head;
}
Node* insertNodeRec(Node *head, int i, int data) {
if(head==NULL)
return NULL;
if(i==0){
Node* temp=new Node(data);
temp->next=head;
return temp;
}
if(i==1){
Node* temp=new Node(data);
temp->next=head->next;
head->next=temp;
return head;
}
insertNodeRec(head->next,i-1,data);
return head;
}
Node* deleteNodeRec(Node *head, int i) {
if(head->next==NULL)
return NULL;
if(i==0){
Node* temp=head->next;
head->next=NULL;
delete head;
return temp;
}
if(i==1){
Node *temp=head->next;
head->next=temp->next;
temp->next=NULL;
delete temp;
return head;
}
deleteNodeRec(head->next,i-1);
return head;
}
int length(Node *head) {
if(head==NULL)
return 0;
int ans=length(head->next);
return ans+1;
}
void print(Node *head)
{
Node *temp = head;
while(temp != NULL)
{
cout<<head -> data<<endl;
head = head -> next;
}
}
int main()
{
Node *head = take_input2();
print(head);
int i,data;
cin>>i;
head = deleteNodeRec(head, i );
print(head);
}