Thursday, January 17, 2008

Finding the middle of a single linked list

Node* MidOfLLUsing2Ptrs(Node *head)
{
Node* OneHop;
Node* TwoHop;
//If no node return NULL
if(head == NULL)
return NULL;
//If only one node then that is the middle
if(head->next == NULL)
return head;
OneHop = head;
TwoHop = OneHop->next;
while((TwoHop != NULL)&&(TwoHop->next != NULL))
{
OneHop = OneHop->next;
TwoHop = TwoHop->next->next;
}
return OneHop;
}


Calling the function:
Node *MidOne = MidOfLLUsing2Ptrs(head);


Complexity: SIMPLE.

No comments: