// c code to find middle element using two pointer technique
struct Node {
int data ;
struct Node* next ;
};
typedef Node* Node ;
Node middleNodeOfLinkedList(Node head)
{
Node slowPtr = fastPtr = head ;
if(head->next != NULL )
{
fastPtr = fastPtr->next->next;
}
while (fastPtr != NULL )
{
// check for more nodes at the node pointed by fastPtr
if(fastPtr -> next != NULL)
{
//advance fastPtr
fastPtr = fastPtr->next->next ;
}
else {
return slowPtr;
}
//advance slow ptr
slowPtr = slowPtr->next ;
}
return slowPtr;
}
struct Node {
int data ;
struct Node* next ;
};
typedef Node* Node ;
Node middleNodeOfLinkedList(Node head)
{
Node slowPtr = fastPtr = head ;
if(head->next != NULL )
{
fastPtr = fastPtr->next->next;
}
while (fastPtr != NULL )
{
// check for more nodes at the node pointed by fastPtr
if(fastPtr -> next != NULL)
{
//advance fastPtr
fastPtr = fastPtr->next->next ;
}
else {
return slowPtr;
}
//advance slow ptr
slowPtr = slowPtr->next ;
}
return slowPtr;
}
No comments:
Post a Comment