-
Notifications
You must be signed in to change notification settings - Fork 0
/
Delete Middle of Linked List.cpp
64 lines (56 loc) · 1.17 KB
/
Delete Middle of Linked List.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
/*
Method - 1
Recursion
Time complexity - O(N)
Space complexity- O(N)
*/
class Solution{
public:
int node = 0;
int count = 0;
Node* deleteRecur(Node* head){
if(!head)
return NULL;
count++;
head->next=deleteRecur(head->next);
node++;
return node==(count%2 ? count/2 + 1 : count/2) ? head->next : head;
}
Node* deleteMid(Node* head)
{
return deleteRecur(head);
}
};
/*
Method - 2
Iterative
Time complexity - O(N/2)
Space complexity- O(1)
*/
class Solution{
public:
Node* deleteMid(Node* head)
{
if (head == NULL or head->next == NULL)
return NULL;
Node* slow=head;
Node* fast=head;
Node* pre=NULL;
while(fast->next and fast->next->next)
{
fast=fast->next->next;
pre=slow;
slow=slow->next;
}
if(fast and fast->next)
{
fast=fast->next;
pre=slow;
slow=slow->next;
}
Node* nextNode=slow->next;
delete slow;
pre->next=nextNode;
return head;
}
};