TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
median_search2.cpp
Go to the documentation of this file.
1
25#include <cassert>
26#include <iostream>
27
31struct ListNode {
32 int val{0};
33 ListNode* next{nullptr};
34 ListNode() = default;
35 explicit ListNode(int x)
36 : val(x) {}
38 : val(x),
39 next(next) {
40 }
41};
42
47namespace search {
53namespace median_search2 {
60 if (!head) {
61 return nullptr;
62 }
63
64 // Fast and slow pointers
65 ListNode* fastptr = nullptr;
66 ListNode* slowptr = fastptr = head;
67
68 // fast jumps 2 while slow jumps 1
69 while (fastptr->next && fastptr->next->next) {
70 slowptr = slowptr->next;
71 fastptr = fastptr->next->next;
72 }
73
74 return (fastptr->next) ? slowptr->next : slowptr;
75}
76
77void deleteAll(const ListNode* const head) {
78 if (head) {
79 deleteAll(head->next);
80 delete head;
81 }
82}
83} // namespace median_search2
84} // namespace search
85
90static void test() {
91 auto* head1 = new ListNode;
92 head1->val = 1;
93
94 ListNode* temp = head1;
95 for (int i = 2; i < 6; ++i) {
96 // Allocate next
97 auto* temp1 = new ListNode;
98 temp1->val = i;
99
100 // Advance
101 temp->next = temp1;
102 temp = temp1;
103 }
104 temp->next = nullptr;
105
106 const ListNode* const median = search::median_search2::middleNode(head1);
107 assert(3 == median->val); // 3 is the value of the median node.
108 search::median_search2::deleteAll(head1);
109 std::cout << "test case:1 passed\n";
110
111 // Test case # 2
112 auto* head2 = new ListNode;
113 head2->val = 1;
114
115 ListNode* temp2 = head2;
116 for (int i = 2; i < 7; ++i) {
117 // Allocate next
118 auto* temp3 = new ListNode;
119 temp3->val = i;
120
121 // Advance
122 temp2->next = temp3;
123 temp2 = temp3;
124 }
125 temp2->next = nullptr;
126
127 const ListNode* const median1 = search::median_search2::middleNode(head2);
128 assert(4 == median1->val); // 4 is the value of the median node.
129 search::median_search2::deleteAll(head2);
130 std::cout << "test case:2 passed\n";
131
132 std::cout << "--All tests passed--\n";
133}
134
139int main() {
140 test(); // run self-test implementations
141 return 0;
142}
ListNode * middleNode(ListNode *head)
static void test()
Self-test implementations.
int main()
Main function.
for std::assert
for IO operations
ListNode()=default
default constructor
int val
the value stored in the node
ListNode(int x)
constructor with value for node->val provided
ListNode * next
pointer to the next node
ListNode(int x, ListNode *next)
constructor with values provided for node->val and node->next