注意分情况讨论:
1. 要删除的不是尾节点
2. 链表只有一个节点
3. 链表中有多个节点,删除尾节点
1 void DeleteNode(ListNode** pListHead, ListNode* pToBeDeleted) 2 { 3 if(!pListHead || !pToBeDeleted) 4 return; 5 6 // 要删除的结点不是尾结点 7 if(pToBeDeleted->m_pNext != NULL) 8 { 9 ListNode* pNext = pToBeDeleted->m_pNext; 10 pToBeDeleted->m_nValue = pNext->m_nValue; 11 pToBeDeleted->m_pNext = pNext->m_pNext; 12 13 delete pNext; 14 pNext = NULL; 15 } 16 // 链表只有一个结点,删除头结点(也是尾结点) 17 else if(*pListHead == pToBeDeleted) 18 { 19 delete pToBeDeleted; 20 pToBeDeleted = NULL; 21 *pListHead = NULL; 22 } 23 // 链表中有多个结点,删除尾结点 24 else 25 { 26 ListNode* pNode = *pListHead; 27 while(pNode->m_pNext != pToBeDeleted) 28 { 29 pNode = pNode->m_pNext; 30 } 31 32 pNode->m_pNext = NULL; 33 delete pToBeDeleted; 34 pToBeDeleted = NULL; 35 } 36 }