【1】题目
【2】思路
删除的链表节点有四种情况:
(1)空链表,返回无;
(2)一个节点,头尾一样,删除节点,头尾清零;
(3)尾部节点,需要遍历链表,找到前一个节点,然后删除后一个节点。
(4)中间任意位置节点,找到待删除节点的下一个节点,用下一个节点覆盖当前节点,然后删除后一个节点即可。
【3】代码
#include <stdio.h>
#include <iostream>
#include<vector>
#include<time.h>
#include<cstring>
using namespace std;
struct ListNode
{
int m_nValue;
ListNode *m_pNext;
};
//删除指定位置的节点 *plistHead是指向头节点的指针
void DeleteNode(ListNode* * plistHead, ListNode *pToDeleted)
{
//指针为空
if (!plistHead|| !pToDeleted)
{
return;
}
//[1]待删除的节点不是最后一个节点
if (pToDeleted->m_pNext!=NULL)
{
ListNode *p_next = pToDeleted->m_pNext;
pToDeleted->m_nValue = p_next->m_nValue;
pToDeleted->m_pNext = p_next->m_pNext;
delete p_next;
p_next = NULL;
}
//[2]删除的节点即使头结点也是尾节点
else if (pToDeleted->m_pNext == NULL)
{
delete pToDeleted;
pToDeleted = NULL;
*plistHead = NULL;
}
//[3]待删除的节点是最后一个节点
else if (pToDeleted->m_pNext == NULL)
{
delete pToDeleted;
pToDeleted = NULL;
*plistHead = NULL;
}
//[4]删除的节点是最后一个尾节点,需要找到前一个节点
else
{
//寻找被删除节点的上一个节点
ListNode *head = *plistHead;
while (head->m_pNext!= pToDeleted)
{
head = head->m_pNext;
}
head->m_nValue = pToDeleted->m_nValue;
head->m_pNext = NULL;
delete pToDeleted;
pToDeleted= NULL;
}
}