【LeetCode】876. 链表的中间结点

给定一个带有头结点 head 的非空单链表,返回链表的中间结点。

如果有两个中间结点,则返回第二个中间结点。

方法1:遍历链表得到链表的长度,计算出中间节点的位置,再次从头结点遍历到中间节点的位置

ListNode* Solution::middleNode(ListNode* phead)
{
    unsigned int length = 0;
    unsigned int index = 0;
    ListNode *plength = phead;
    ListNode *newhead = new ListNode(0);
    
    if((phead == NULL)||(phead->next == NULL))
    {
        return phead;
    }
    while(plength != NULL)
    {
        plength = plength->next;
        length ++;
    }
    if(1u == length)
    {
        return phead;
    }
    else
    {
        ListNode *pmiddle = phead->next;
        for(index = 0; index < length / 2 ; index ++)
        {
            pmiddle = pmiddle->next;
        }
        newhead->next = pmiddle;
        return newhead;
    }
}

2.利用快慢指针,一次遍历中找到中间节点,需要注意的是:如果有两个中间结点,则返回第二个中间结点。

ListNode* Solution::NewmiddleNode(ListNode* phead)
{
    ListNode *pfast = phead;
    ListNode *pslow = phead;
    while((pfast->next != NULL) && (pfast->next->next != NULL))
    {
        pslow = pslow->next;
        pfast = pfast->next->next;
    }
    if(pfast->next == NULL)
    {
        return pslow;
    }
    else
    {
        return pslow->next;
    }
}

猜你喜欢

转载自blog.csdn.net/syc233588377/article/details/85088350