欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

203. Remove Linked List Elements

程序员文章站 2024-02-19 08:36:18
...

203. Remove Linked List Elements

方法1: iterative

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if (!head) return head;
        ListNode * prev = new ListNode(-1);
        ListNode * newHead = prev;
        prev -> next = head;
        while (head){
            if (head -> val == val) {
                prev -> next = head -> next;
                head = head -> next;
            }
            else {
                 prev = prev -> next;
                head = head -> next;
            }
           
        }
        return newHead->next;
    }
};

方法2: recursion

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