[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

跟上一题有点像,不过多增加前面的一些判断,遍历链表的循环里的判断变为val。

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if(!head) return NULL;
        while (head->val == val){
            head = head->next;
            if(!head) return NULL;
        }
        
        ListNode* cur = head;
        
        while (cur){
            if (cur->next == NULL) break;
            if (cur->next->val == val){
                cur->next = cur->next->next;
            }
            else{
                cur = cur->next;
            }
        }
        return head;
    }
};

 

posted on 2016-09-04 10:51  医生工程师  阅读(139)  评论(0编辑  收藏  举报

导航