Thursday, July 30, 2015

Leetcode 203: remove linked list elements

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

这个题目很简单,要特殊注意的地方就是当链表的head被删除时,可能要进行特殊的处理,所以我们可以用一个dummy head来统一corner case。 其他没有特殊的地方,即使是要被删除的节点连续也是可以generally handle的。

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        //sanity check
        if (head == NULL) return NULL;
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* pre = dummy;
        ListNode* cur = head;
        while (cur) {
            if (cur->val == val) {
                pre->next = cur->next;
            } else {
                pre = cur;
            }
            cur = cur->next;
        }
        return dummy->next;
    }
};

No comments:

Post a Comment