链表面试题2

查找单链表的中间节点,要求只能遍历一次链表

思路:创建两个指针,Fast,Slow. Fast每次走的节点数是Slow的两倍,当Fast == NULL||Fast->next == NULL(因为有时候链表节点是偶数,有时候是奇数所以需要两个条件)时返回Slow,此时Slow所指向的节点就是中间节点

ListNode* FindMiddleNode(ListNode* p1)//查找单链表的中间节点,只遍历一次链表
{
    ListNode* pFast = p1;
    ListNode* pSlow = p1;
    while (pFast && pFast->next)
    {
        pFast = pFast->next->next;
        pSlow = pSlow->next;
    }
    return pSlow;
}

查找的单链表的倒数第K个节点,只遍历一次链表

思路:确定两个节点Fast,Slow。让Fast比Slow先走K个节点,之后两个节点一起走,知道Fast == NULL,这个时候Slow就是倒数第K个节点

ListNode* FindLastNode(ListNode* p1, int k)//查找的单链表的倒数第K个节点,只遍历一次链表
{
    ListNode* pFast = p1;
    ListNode* pSlow = p1;
    if (p1 == NULL || k < 0)
    {
        return NULL;
    }
    while (k--)
    {
        if (pFast == NULL)
            return NULL;
        pFast = pFast->next;
    }
    while (pFast)
    {
        pFast = pFast->next;
        pSlow = pSlow->next;
    }
    return pSlow;
}

删除单链表的倒数第K个节点

用上面的方法找到倒数k-1个节点,然后删除

void DelLastNode(ListNode* p1, int k)//删除单链表的倒数第K个节点
{
    ListNode* pFast = p1;
    ListNode* pSlow = p1;
    ListNode* Del = NULL;
    int flag = 0;
    if (p1 == NULL || k < 0)
    {
        return NULL;
    }
    while (k--)
    {
        if (pFast == NULL)
            return NULL;
        pFast = pFast->next;
    }
    while (pFast)
    {
        if (flag++ != 0)
        {
            pSlow = pSlow->next;
        }
        pFast = pFast->next;
    }
    Del = pSlow->next;
    pSlow->next = pSlow->next->next;
    free(Del);
    Del = NULL;
}

猜你喜欢

转载自blog.csdn.net/qq_39032310/article/details/82081796
今日推荐