码迷,mamicode.com
首页 > 其他好文 > 详细

在O(1)时间删除链表结点

时间:2015-08-12 19:24:00      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:链表

 给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点.链表结点与函数定义如下:
 

struct ListNode
{
    int m_nValue;
    ListNode* m_pNext;
};

code:


//把待删结点后面一个结点的值赋给待删结点,然后把待删结点next指针指向下下个结点,然后删除下个结点, 达到和删除待删结点一样的效果.



void DeleteNode(ListNode** pListHead, ListNode* pToBeDeleted)
{
    if (!pListHead || !pToBeDeleted)
        return;
    //链表仅有一个结点就是待删结点
    if (*pListHead == pToBeDeleted &&  pToBeDeleted->m_pNext == NULL)
    {
        delete pToBeDeleted;
        pToBeDeleted = NULL;
        *pListHead = NULL;
    }
    //链表不止一个结点并且要删除的结点是头节点
    else if (*pListHead == pToBeDeleted)
    {
        *pListHead = (*pListHead)->m_pNext;
        delete pToBeDeleted;
        pToBeDeleted = NULL;
    }
   //要删除的结点是最后一个结点
    else if (pToBeDeleted->m_pNext == NULL)
    {
        ListNode* pTmp = *pListHead;
        while (pTmp->m_pNext != pToBeDeleted)
        {
            pTmp = pTmp->m_pNext;
        }
        pTmp->m_pNext = NULL;
        delete pToBeDeleted;
        pToBeDeleted = NULL;
        pTmp = NULL;
    }
    //待删除结点为正常结点
    else
    {
        ListNode* pNext = pToBeDeleted->m_pNext;
        pToBeDeleted->m_nValue = pNext->m_nValue;
        pToBeDeleted->m_pNext = pNext->m_pNext;
        delete pNext;
        pNext = NULL;
    }

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

在O(1)时间删除链表结点

标签:链表

原文地址:http://blog.csdn.net/nizhannizhan/article/details/47448909

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!