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

struct ListNode
{
	int nValue;
	ListNode* pNext;
};

void DeleteListNode(ListNode* pHeadNode, ListNode* pDeleteNode)
{
	if (!pHeadNode || !pDeleteNode)
		return;

	if (pHeadNode == pDeleteNode)    
	{
		delete pDeleteNode;
		pDeleteNode = nullptr;
		pHeadNode = nullptr;
	}
	else if (pDeleteNode->pNext == nullptr)
	{
		ListNode* pTempNode = pHeadNode;
		while (pTempNode->pNext != pDeleteNode)
		{
			pTempNode = pTempNode->pNext;
		}
		pTempNode->pNext = pDeleteNode->pNext;
		delete pDeleteNode;
		pDeleteNode = nullptr;
	}
	else
	{
		ListNode* pTempNode = pDeleteNode->pNext;
		pDeleteNode->nValue = pTempNode->nValue;
		pDeleteNode->pNext = pTempNode->pNext;
		delete pTempNode;
		pTempNode = nullptr;
	}
}

  

posted on 2021-02-08 17:31  Noora&w  阅读(48)  评论(0编辑  收藏  举报