题目
解法
1.双指针
struct ListNode* removeElements(struct ListNode* head, int val) {
if(!head)
return head;
struct ListNode* cur = head;
struct ListNode* pre = head;
while(cur)
{
if(head->val == val)
head = head->next;
if(cur->val == val)
pre->next = cur->next;
else
pre = cur;
cur = cur->next;
}
return head;
}
2.递归
struct ListNode* removeElements(struct ListNode* head, int val) {
if(!head)
return head;
struct ListNode* ans = removeElements(head->next ,val);
if(head->val == val)
return ans;
else{
head->next = ans;
return head;
}
}
3.虚拟头节点
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode *dummyHead = (struct ListNode*)malloc(sizeof(struct ListNode));
if (NULL == dummyHead) {
return NULL;
}
dummyHead->next = head;
struct ListNode* cur = dummyHead;
while (cur->next != NULL)
{
if (cur->next->val == val)
cur->next = cur->next->next;
else
cur = cur->next;
}
struct ListNode* ans = dummyHead->next;
free(dummyHead);
return ans;
}