Created
September 14, 2023 03:46
-
-
Save AlexDev404/8f2bd052cb199d9d71bb032eb6c7a4b1 to your computer and use it in GitHub Desktop.
Find the middle of a linked list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void printMiddle(Node* head) { | |
if (head == NULL) { | |
// Return because the list is empty | |
return; | |
} | |
Node* slow_ptr = head; // This will traverse the list one element at a time | |
Node* fast_ptr = head; // This will go through the list two elements at a time | |
while (fast_ptr != NULL && fast_ptr->next != NULL) { | |
slow_ptr = slow_ptr->next; // Next | |
fast_ptr = fast_ptr->next->next; // Next next | |
} | |
// Once the fast pointer hits the end the slower pointer should have the data of the midle element | |
std::cout << slow_ptr->data << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment