Leetcode: Remove Linked List Elements

来源:互联网 发布:sql 用变量作为字段名 编辑:程序博客网 时间:2024/06/05 09:32


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

简单。

/** * 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) {        while (head != nullptr && head->val == val) {            head = head->next;        }        if (head == nullptr) {            return head;        }                ListNode* prev = head;        ListNode* cur = head->next;        while (cur != nullptr) {            if (cur->val != val) {                prev->next = cur;                prev = cur;            }            cur = cur->next;        }        prev->next = nullptr;                return head;    }};

Hack的方法,直接移动值。

/** * 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) {        ListNode* cur = head;        ListNode* prev = head;        ListNode* tail = nullptr;        while (cur != nullptr) {            if (cur->val != val) {                prev->val = cur->val;                tail = prev;                prev = prev->next;            }            cur = cur->next;        }        if (tail != nullptr) {            tail->next = nullptr;        }        else {            head = nullptr;        }        return head;    }};


0 0