-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathMiddleNode.cpp
90 lines (67 loc) · 1.8 KB
/
MiddleNode.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
// Find the middle node of a singly linked list
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node() {
this->next = NULL;
}
Node(int data) {
this->data = data;
this->next = NULL;
}
};
class LinkedList {
public:
Node* head = NULL;
void insert_at_beg(int data){
Node* temp = new Node(data);
temp->next = this->head;
this->head = temp;
}
void print_data(){
Node* itr = this->head;
while(itr != NULL){
cout << itr->data << " ";
itr = itr->next;
}
cout << endl;
}
};
Node* middle_node(LinkedList* ll){
Node *fast = ll->head, *slow = ll->head;
// if list is empty or only 1 node is present
if(fast == NULL || fast->next == NULL)
return fast;
// while the double speed pointer doesn't get to the end
// keep updating both slow and fast pointers
while(fast != NULL){
fast = fast->next;
if(fast != NULL){
fast = fast->next;
slow = slow->next;
}
}
return slow;
}
int main() {
LinkedList* ll = new LinkedList();
// Create Linked list
ll->insert_at_beg(7);
ll->insert_at_beg(6);
ll->insert_at_beg(5);
ll->insert_at_beg(4);
ll->insert_at_beg(3);
ll->insert_at_beg(2);
ll->insert_at_beg(1);
cout<<"Linked List data:\n";
ll->print_data();
cout << "Middle of the linked list is: " << middle_node(ll)->data << endl;
ll->insert_at_beg(0);
cout<<"Linked List data:\n";
ll->print_data();
cout << "Middle of the linked list is: " << middle_node(ll)->data << endl;
return 0;
}