给定单向链表的头指针和一个结点指针,定义一个函数在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;
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-10 16:37:26