这种一般有两种方法,第一种就是先判断头节点,之后判断除了头节点以外其他节点
struct ListNode* removeElements(struct ListNode* head, int val){
while (NULL != head && head->val == val) {
head = head->next;
}
if (NULL == head) {
return head;
}
struct ListNode* pre = head;
while (pre->next != NULL) {
/* 找到值为 val 的节点,并将其删除 */
if (pre->next->val == val) {
pre->next = pre->next->next;
} else {
/* 没找到,则继续遍历查找 */
pre = pre->next;
}
}
return head;
}
第二种就是构造一个虚拟头节点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
typedef struct ListNode ListNode;
ListNode *shead;
shead = (ListNode *)malloc(sizeof(ListNode));
shead->next = head;
ListNode *cur = shead;
while(cur->next != NULL){
if (cur->next->val == val){
ListNode *tmp = cur->next;
cur->next = cur->next->next;
free(tmp);
}
else{
cur = cur->next;
}
}
head = shead->next;
free(shead);
return head;
}