题目描述:
给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点 。
方法1:遍历
遍历链表,记录当前结点 cur 和当前结点的前一个结点 pre,如果当前结点的 val 和 val 相等,则删除该结点,删除的步骤就是让前一个结点 pre 的 next 指向当前结点 cur的 next,也就是 pre->next = cur->next,并将 cur 指向 pre->next,即 cur = pre->next.
当头结点的 val 与 val 相等,直接让头结点向后移动。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode* newHead = head;
while(newHead!=NULL && newHead->val==val)
{
newHead = newHead->next;
}
if(newHead==NULL || newHead->next==NULL)
{
return newHead;
}
struct ListNode* pre = newHead;
struct ListNode* cur = newHead->next;
while(cur!=NULL)
{
if(cur->val == val)
{
pre->next = cur->next;
cur = pre->next;
}
else
{
pre = cur;
cur = cur->next;
}
}
return newHead;
}
方法2:递归
首先查看递归的结束条件:如果头结点为0,则返回NULL
如果当前结点等于 val,则将当前结点向后移动一个位置,并用当前结点继续执行函数;
如果当前结点不等于val,则让当前结点的next 继续执行函数;
最后返回的值是当前结点。
struct ListNode* removeElements(struct ListNode* head, int val){
if(head==NULL)
{
return NULL;
}
if(head->val!=val)
{
head->next = removeElements(head->next, val);
}
else
{
head = head->next;
head = removeElements(head, val);
}
return head;
}