Skip to content

Instantly share code, notes, and snippets.

@AlexDev404
Created September 14, 2023 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlexDev404/8f2bd052cb199d9d71bb032eb6c7a4b1 to your computer and use it in GitHub Desktop.
Save AlexDev404/8f2bd052cb199d9d71bb032eb6c7a4b1 to your computer and use it in GitHub Desktop.
Find the middle of a linked list
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