Remove Linked List Elements leetcode

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

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

 

Subscribe to see which companies asked this question

依然是利用快慢两个指针,这里注意头结点设置为临时局部变量
ListNode* removeElements(ListNode* head, int val) {
    ListNode dummy(0);
    dummy.next = head;
    ListNode* slow = &dummy, *fast = head;
    while (fast != nullptr)
    {
        if (fast->val != val)
        {
            slow->next = fast;
            slow = slow->next;
        }
        fast = fast->next;
    }
    slow->next = nullptr;
    return dummy.next;
}

 

posted @ 2016-01-04 20:24  sdlwlxf  阅读(108)  评论(0编辑  收藏  举报