203 remove linked list elements

简单明了,但要注意删除头节点的情况,最好使用dummy头

struct ListNode* removeElements(struct ListNode* head, int val) {
    if(head == NULL)
        return NULL;

    struct ListNode *prev, *curr;
    struct ListNode *dummyhead = malloc(sizeof(struct ListNode));
    dummyhead->next = head;
    prev = dummyhead;
    curr = dummyhead->next;

    while(curr){
        if(curr->val == val){
            prev->next = curr->next;
            curr = prev->next;
        }else{
            curr = curr->next;
            prev = prev->next;
        }

    }

    return dummyhead->next;
}

你可能感兴趣的:(203 remove linked list elements)