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

//给定单向链表的头指针和一个结点指针,定义一个函数在O(1)时间删除该结点。
1
struct ListNode //结点结构 2 { 3 int m_nValue; 4 ListNode* m_pNext; 5 }; 6 7 void DeleteNode(ListNode** pListHead , ListNode* pToBeDeleted) 8 { 9 if (!pListHead || !pToBeDeleted) 10 { 11 return; 12 } 13 if (pToBeDeleted->m_pNext != NULL) 14 { 15 ListNode* pNext = pToBeDeleted->m_pNext ; 16 pToBeDeleted->m_nValue = pNext->m_nValue; 17 pToBeDeleted->m_pNext = pNext->m_pNext; 18 delete pNext; 19 pNext = NULL; 20 } 21 else if (*pListHead == pToBeDeleted)//只有一个结点 22 { 23 delete pToBeDeleted; 24 pToBeDeleted = NULL; 25 *pListHead = NULL; 26 } 27 else //尾结点 28 { 29 ListNode* pNode = *pListHead ; 30 while (pNode->m_pNext != pToBeDeleted) 31 { 32 pNode = pNode->m_pNext; 33 } 34 pNode->m_pNext = NULL ; 35 delete pToBeDeleted; 36 pToBeDeleted = NULL ; 37 } 38 } 39 40

 

 

你可能感兴趣的:(链表)