-
Notifications
You must be signed in to change notification settings - Fork 0
/
middle_of_LL.cpp
89 lines (77 loc) · 1.73 KB
/
middle_of_LL.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
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int data = 0){
this->data = data;
this->next = NULL;
}
};
void print(Node* &head){
Node* temp = head;
while(temp){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
int length(Node* head){
Node* temp = head;
int n = 0;
while(temp){
n++;
temp = temp->next;
}
return n;
}
// Two Pointer Approach
// slow-fast pointer approach
// tortoise algorithm
Node* findMiddle(Node* head){
if(!head || !head->next)
return head;
Node* slow = head; // slow ptr moves 1 steps
Node* fast = head; // fast ptr moves 2 steps
while(slow && fast){
fast = fast->next;
if(fast != NULL){
fast = fast->next;
slow = slow->next;
}
}
return slow;
}
// Navie Approach
Node* findMiddle_01(Node* head){
if(!head || !head->next)
return head;
int len = length(head);
int i = 0;
Node* temp = head;
while(i < len/2){
temp = temp->next;
i++;
}
return temp;
}
int main()
{
Node* head = new Node(10);
Node* first = new Node(20);
Node* second = new Node(30);
Node* third = new Node(40);
Node* forth = new Node(50);
// Node* fifth = new Node(60);
head->next = first;
first->next = second;
second->next = third;
third->next = forth;
forth->next = NULL;
// fifth->next = NULL;
print(head);
cout<<"Middle: "<<findMiddle(head)->data<<endl;
cout<<"Middle: "<<findMiddle_01(head)->data<<endl;
return 0;
}