LeetCode | 203. Remove Linked List Elements

1LOVESJohnny發表於2020-11-30

 

題目:

Remove all elements from a linked list of integers that have value val.

Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

 

程式碼:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if(head == NULL)
            return head;
        ListNode *search = head, *record = new ListNode(-999);
        while(search != NULL)
        {
            if(search->val == val)
            {
                record->next = search->next;
                if(head == search)
                {
                    head = search->next;
                }
            }
            else
            {
                record->next = search;
                record = record->next;
            }
            search = search->next;
        }
        return head;
    }
};

 

又是一次AC~並且效率優於98%~

 

 

 

相關文章