forked from BabesGotByte/Coding_SkillSet_Topicwise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnswer26.cpp
57 lines (46 loc) · 915 Bytes
/
Answer26.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
#include <iostream>
template <typename T>
class node {
public:
struct node* next;
T value;
node(T value, node* next) {
this->value = value;
this->next = next;
}
node(T value) {
this->value = value;
this->next = nullptr;
}
};
/*
Returns the middle node for a given linked list.
This implementation is not thread-safe.
*/
template <typename T>
node<T>* getMiddleNode(node<T>* list) {
node<T>* middle = list;
int count = 0;
// Count list elements
while(list) {
list = list->next;
count++;
}
std::cout << "COUNT " << count << std::endl;
// Jump to the middle element
while(count > 1 && middle) {
middle = middle->next;
count -= 2;
}
return middle;
}
int main() {
// 9 -> 8 -> 7 -> 6 -> 5
node<int> a(5);
node<int> b(6, &a);
node<int> c(7, &b);
node<int> d(8, &c);
node<int> e(9, &d);
std::cout << getMiddleNode(&e)->value << std::endl;
return 0;
}