第一种方式 :删除原链表的指定元素 第二种方式 :创建新链表 尾插不属于指定元素的节点
这里只介绍第二种方式,因为更为简洁高效
struct ListNode {
int val;
struct ListNode* next;
};
struct ListNode* removeElements(struct ListNode* head, int val)
{
struct ListNode* newhead, * newtail;//创建新链表的头指针尾指针
newhead = newtail = NULL;//初始化
struct ListNode* pcur = head;//遍历原链表的指针
while (pcur)
{
if (pcur->val != val)//先判断是否是要删除的要素
{
if (newhead == NULL)//如果不是要删除的元素,并且新链表为空
{
newhead = newtail = pcur;//新链表首尾指针都指向该节点
}
else
{
newtail->next = pcur;//将该节点插入到新链表
newtail = newtail->next;
}
}
pcur = pcur->next;//pcur向后移动
}
if (newtail)//先判空是为了保证不是空链表
{
newtail->next = NULL;//将尾节点next指针指向NULL
}
return newhead;
}