leetcode-203-Remove Linked List Elements

1110 ワード

Description:
Remove all elements from a linked list of integers that have value value.Example Given:1-->2-->6-->3-->4-->5-->6、val=6 Return:1-->2-->3-->5題意:単一チェーンテーブルと数を与え、チェーンテーブル内のこの数に等しいすべてのノードを削除する
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeElements(struct ListNode* head, int val) {
    struct ListNode* temp;
    while(head!=NULL && head->val == val){
        temp = head->next;
        free(head);
        head = temp;
    }
    if(head==NULL) {
        return head;
    }
    struct ListNode* pre = head;
    struct ListNode* cur = head->next;
    while(cur != NULL) {
        if(cur->val == val) {
            temp = cur->next;
            free(cur);
            cur = temp;
           pre->next = cur;
        } else {
            pre = pre->next;
            cur = cur->next;
        }
    }
    return head;
}

この問題は難しくありません.主に、単一チェーンテーブルのノードを削除するには、前のノードのnextが削除されたノードの次のノードを指すように、遍歴するときに前のノードを覚えなければなりません.