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

题解:链表的操作有两个常用的技巧:第一就是用递归,第二就是开一个新节点指向头指针来方便一些操作。

本题也是递归和非递归两种方法:

非递归:

/**
 * 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==nullptr)return head;
        ListNode* p=new ListNode(0);
        p->next=head;
        ListNode* cur=p;
        while(cur&&cur->next){
            if(cur->next->val==val){
                cur->next=cur->next->next;
            }
            else{
                cur=cur->next;
            }
        }
        return p->next;
    }
};

这里有一个值得思考的地方:在leetcode 237. Delete Node in a Linked List这道题中,我们不知道一个节点的前驱节点,但是也可以通过让该节点等于它后一个节点的方式间接的删除该节点。那么这道题可不可以这样呢?

答案是否定的,因为那道题有一个限制是:要删除的节点肯定不是最后一个节点。因为如果是最后一个节点,我们就必须通过把它的前驱节点的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==nullptr){
            return head;
        }
        if(head->val==val){
            return removeElements(head->next,val);
        }
        head->next=removeElements(head->next,val);
        return head;
    }
};
原文地址:https://www.cnblogs.com/zywscq/p/5429168.html