TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
|
Given a linked list L[0,....,n] of n numbers, find the middle node. More...
#include <cassert>
#include <iostream>
Go to the source code of this file.
Classes | |
struct | ListNode |
for IO operations More... | |
Namespaces | |
namespace | search |
for std::assert | |
namespace | median_search |
Functions for Median search algorithm. | |
Functions | |
ListNode * | search::median_search2::middleNode (ListNode *head) |
void | search::median_search2::deleteAll (const ListNode *const head) |
static void | test () |
Self-test implementations. | |
int | main () |
Main function. | |
Given a linked list L[0,....,n] of n numbers, find the middle node.
The technique utilized in this implementation is the ["Floyd's tortoise and hare"](https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare) approach. This technique uses two pointers that iterate through the list at different 'speeds' in order to solve problems. In this implementation, for every iteration the slow pointer advances one node while the fast pointer advances two nodes. The result of this is that since the fast pointer moves twice as fast as the slow pointer, when the fast pointer reaches the end of the list the slow pointer will be pointing to the middle node of the list.
Here are some example lists you can use to see how the algorithm works A = [1,2,3,4,5] B = [1,2,3,4,5,6] print median(A) #should be 39 print median(B) #should be 4
Definition in file median_search2.cpp.
void search::median_search2::deleteAll | ( | const ListNode *const | head | ) |
Definition at line 77 of file median_search2.cpp.
int main | ( | void | ) |
Main function.
Definition at line 139 of file median_search2.cpp.
This function searches for the median of a linked list.
head | The head of the linked list. |
Definition at line 59 of file median_search2.cpp.
|
static |
Self-test implementations.
Definition at line 90 of file median_search2.cpp.