#include <iostream>
struct ListNode
{
int value;
ListNode* pnext;
ListNode(int value, ListNode* node) :value(value), pnext(node)
{
}
};
void traverseList(ListNode *head)
{
while (head != NULL)
{
std::cout << head->value << " ";
head = head->pnext;
}
std::cout << std::endl;
}
ListNode* remove(ListNode * head, int target)
{
if (head == NULL) return NULL;
//改造成头节点链表
ListNode *dump = new ListNode(-1, nullptr);
dump->pnext = head;
//鉴别是否要进行删除的接点的前一个结点,也就是当前判断处理节点的前一个节点
ListNode *pre = dump;
//依次用cur遍历链表中的每一个节点,pre就是cur的前一个节点
ListNode *cur = head;
while (cur != NULL)
{
if (cur->value == target)
{
pre->pnext = cur->pnext;
//考虑空间释放的时候,暂时不考虑这个
//ListNode *willFree = cur;
//cur = cur->pnext;
//free(willFree);
}
else
{
pre = cur;
}
cur = cur->pnext;
}
return dump->pnext;
}
int main()
{
ListNode * node1 = new ListNode(7, nullptr);
ListNode * node2 = new ListNode(2, nullptr);
ListNode * node3 = new ListNode(3, nullptr);
ListNode * node4 = new ListNode(7, nullptr);
ListNode * node5 = new ListNode(5, nullptr);
ListNode * node6 = new ListNode(6, nullptr);
ListNode * node7 = new ListNode(7, nullptr);
node1->pnext = node2;
node2->pnext = node3;
node3->pnext = node4;
node4->pnext = node5;
node5->pnext = node6;
node6->pnext = node7;
ListNode *head = node1;
int target = 7;
traverseList(head);
ListNode *newHead = remove(head, target);
traverseList(newHead);
}