Find the nodes in the singly linked list Tencent interview questions

Quickly find the intermediate node in the single linked list of unknown length

1. Ordinary method
First, you need to traverse the linked list, then know the length of the linked list, and then re-find the node of the intermediate length, and then output the node value. The algorithm complexity is O(n)+O(1/2n). There is no ordinary code demonstration here.
2. Method of adding points
Using the method of fast and slow pointers, the *fast pointer moves two nodes at a time, and the slow pointer moves one node at a time. When the fast pointer reaches the end, the *slow pointer is just at the middle node in the singly linked list. In this way, the complexity of the algorithm is only O(1/2n), and the efficiency is increased by three times. code show as below:

status GetMidNode(LinkList L,ElemType *e)
{
    
    
    L.inkList fast,slow;
    slow = fast = L;
    while (fast->next != NUIL)
    {
    
    
        if(fast->next->next !=NULL)
        {
    
    
            fast= fast->next->next;
            slow = slow->next;
        }
       else
       {
    
    
           fast = fast->next;
       }
    }
   *e = mid->data;
    return Ok;
}

Guess you like

Origin blog.csdn.net/qq_51344334/article/details/119783105