Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 –> 5
1、头节点特殊处理
/** * 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* tmp = head; struct ListNode* tmp2 = NULL; while(head->val == val) { tmp2 = head; head = tmp2->next; free(tmp2); if(head == NULL) return NULL; tmp = head; } while(tmp->next != NULL) { if(tmp->next->val == val) { tmp2 = tmp->next; tmp->next = tmp2->next; free(tmp2); } else tmp = tmp->next; } return head; }
2、使用一个指向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* tmp = malloc(sizeof(struct ListNode)); tmp->next = head; head = tmp; struct ListNode* tmp2 = NULL; while(tmp->next != NULL) { if(tmp->next->val == val) { tmp2 = tmp->next; tmp->next = tmp2->next; free(tmp2); } else tmp = tmp->next; } return head->next; }
3、先处理普通情况,最后处理head
struct ListNode* removeElements(struct ListNode* head, int val) { if (head == NULL) return NULL; struct ListNode *cur = head, *next = head->next; while (next != NULL) { if (next->val == val) { cur->next = next->next; next = cur->next; } else { cur = cur->next; next = next->next; } } if (head->val == val) { cur = head; head = head->next; } return head; }
看到最后评分还是不高,不知道更好的方法是什么。。。