删除链表中等于给定值 val 的所有节点。
方法一: 递归法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val) {
if(head == NULL)
{
return NULL;
}
head->next = removeElements(head->next,val);
return head->val == val ? head->next : head;
}
方法二:循环
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
if(head == NULL)
{
return NULL;
}
struct ListNode* cur = head;
while(cur->next)
{
if(cur->next->val == val)
{
struct ListNode* next = cur->next->next;
free(cur->next);
cur->next = next;
}
else
{
cur = cur->next;
}
}
if(head->val == val)
{
struct ListNode* newhead = head ->next;
free(head);
return newhead;
}
return head;
}