Problem solving with programming: Finding the middle of the linked list
Given a single linked list, how do you find the middle of the list?
Fast slow pointer; similar questions: find cycle in list.
Given a single linked list, how do you find the middle of the list?
Fast slow pointer; similar questions: find cycle in list.
SLLNode* getMiddle() { //if the list is empty or has a single node; return head if( head == NULL || head->getNext() == NULL ) return head; SLLNode *slow = head; SLLNode *fast = head->getNext(); while( fast != NULL ) { //move fast pointer two steps ahead if( fast->getNext() != NULL ) { fast = fast->getNext()->getNext(); } else break; //move slow pointer one step slow = slow->getNext(); } return slow; }Read full article from Problem solving with programming: Finding the middle of the linked list