203. Remove Linked List Elements

问题描述:

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

解题思路:

需要注意的是,目标值可能会出现在任意的位置并且出现任意的数量。

用pre来标识目标节点前一个节点,初始化为NULL

即当pre为NULL是发现目标节点,我们需要改变头节点的位置为cur->next

代码:

/**
 * 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) return head;
        ListNode* pre = NULL;
        ListNode* cur = head;
        while(cur){
            if(cur->val == val){
                if(pre) pre->next = cur->next;
                else head = cur->next;
                cur = cur->next;
                continue;
            }
            pre = cur;
            cur = cur->next;
        }
        return head;
    }
};
原文地址:https://www.cnblogs.com/yaoyudadudu/p/9393880.html