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

思路1
为了最后能return修改后的链表,所以我们创建了一个总头dummy,来指向原来链表的head,然后再创造俩个指针,一前一后用来比较

/** * 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* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* p = dummy;
        ListNode* q = head;
        while(q!=NULL)
        {
            if(q->val == val)
                p->next = q->next;
            else
                p = p->next;

            q = q->next;
        }

        return dummy->next;

    }
};

思路2
和上面相反的方法,不用记录Head
新建一个指针来代替head移动,然后释放删除节点。最后再比较第一个节点,然后正好返回Head

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

思路3
递归撒

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

你可能感兴趣的:(203. Remove Linked List Elements)