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

Solution:

/**
 * 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(NULL == head) return head;
        else if(head->val == val) return removeElements(head->next, val);
        else{
            ListNode *p1 = head, *p2 = head->next;
            while(NULL != p2){
                if(p2->val == val){
                    p1->next = p2->next;
                    p2 = p1->next;
                }else{
                    ListNode* t = p2;
                    p2 = p2->next;
                    p1 = t;
                }
            }
            return head;
        }
    }
};

推荐阅读更多精彩内容