题目
菜鸟解答
删除的时候做了free处理。
注意的特殊场景就是 头部连续等于val
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode *scan = head;
struct ListNode *prev= head;
if (NULL == head)
return NULL;
while (head->val == val) { /*注意 头部 连续=val的情况*/
if (NULL == head->next) {
free(head);
return NULL;
}
else {
prev= head;
head = scan = head->next;
free(prev);
}
}
while (scan != NULL) {
if (scan->val == val) {
prev->next = scan->next;
free(scan);
scan = prev->next;
}
else { /*first here*/
prev = scan;
scan = scan->next;
}
}
return head;
}
评论区大神的解答
原评论链接https://leetcode-cn.com/problems/remove-linked-list-elements/solution/203yi-chu-lian-biao-yuan-su-by-lewis-dxstabdzew/
学习法2 和 法3
虚拟头节点 - 省去了对原头节点的单独处理 ORZ
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode *scan;
struct ListNode *prev;
struct ListNode tmp_head; /*虚拟一个头节点*/
if (NULL == head)
return NULL;
tmp_head.val = val - 1;
tmp_head.next = head;
prev = &tmp_head;
scan = tmp_head.next; /*原头节点*/
while (scan != NULL) {
if (scan->val == val) {
prev->next = scan->next;
free(scan);
scan = prev->next;
}
else {
prev = scan;
scan = scan->next;
}
}
return tmp_head.next;
}
递归 - ORZ !
struct ListNode* removeElements(struct ListNode* head, int val){
struct ListNode *next;
struct ListNode *buf;
if (NULL == head)
return NULL;
head->next = removeElements(head->next, val);
if (head->val == val) {
buf = head->next;
free(head);
return buf;
}
else {
return head;
}
}