首页 > 代码库 > 【LeetCode】203. Remove Linked List Elements

【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

题解:

   这道题没什么好讲的,基础操作。需要注意的是链表的第一个node,因为没有前驱节点,所以该node需要特殊处理,会导致额外的代码量。如果创建一个dummy,将其作为第一个node的前驱节点,这样链表中所有的node都可以也能够同样的逻辑来处理了。

Solution 1 ()

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        static ListNode dummy(-1);
        dummy.next = head;
        ListNode *p = &dummy;
        
        while( p->next) {
            if (p->next->val == val) {
                p->next = p->next->next;
            }else{
                p = p->next;
            }
        }
        
        return dummy.next;
    }
};

  这里有个技巧,利用二级指针,操作简洁

Solution 2 ()

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

  还有一种递归的思想

Solution 3 ()

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if (head == null) return null;
        head.next = removeElements(head.next, val);
        return head.val == val ? head.next : head;
    }
};

 最后附上创建链表和打印链表的函数

CreatList

ListNode* createList(vector<int> nums) {
    ListNode *head = NULL, *p = NULL;
    int n = nums.size();
    for(int i=0; i<n; ++i) {
        if(head == NULL) head = p = new ListNode(nums[i]);
        else {
            p->next = new ListNode(nums[i]);
            p = p->next;
        }
    }
    return head;
}

PrintList

void printList(ListNode *head) {
    ListNode *p = head;
    while(p) {
        if(p == head && p) {
            cout << p->val;
            p = p->next;
        }else {
            cout  << "->" << p->val;
            p = p->next;
        }
    }
    delete p;
    cout<<endl;
}

 

【LeetCode】203. Remove Linked List Elements