C++实现LeetCode(203.移除链表元素)

2022-07-22,,,,

[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

credits:
special thanks to for adding this problem and creating all test cases.

这道移除链表元素是链表的基本操作之一,没有太大的难度,就是考察了基本的链表遍历和设置指针的知识点,我们只需定义几个辅助指针,然后遍历原链表,遇到与给定值相同的元素,将该元素的前后连个节点连接起来,然后删除该元素即可,要注意的是还是需要在链表开头加上一个dummy node,具体实现参见代码如下:

解法一:

class solution {
public:
    listnode* removeelements(listnode* head, int val) {
        listnode *dummy = new listnode(-1), *pre = dummy;
        dummy->next = head;
        while (pre->next) {
            if (pre->next->val == val) {
                listnode *t = pre->next;
                pre->next = t->next;
                t->next = null;
                delete t;
            } else {
                pre = pre->next;
            }
        }
        return dummy->next;
    }
};

如果只是为了通过oj,不用写的那么严格的话,下面这种方法更加简洁,当判断下一个结点的值跟给定值相同的话,直接跳过下一个结点,将next指向下下一个结点,而根本不断开下一个结点的next,更不用删除下一个结点了。最后还要验证头结点是否需要删除,要的话直接返回下一个结点,参见代码如下:

解法二:

class solution {
public:
    listnode* removeelements(listnode* head, int val) {
        if (!head) return null;
        listnode *cur = head;
        while (cur->next) {
            if (cur->next->val == val) cur->next = cur->next->next;
            else cur = cur->next;
        }
        return head->val == val ? head->next : head;
    }
};

我们也可以用递归来解,写法很简洁,通过递归调用到链表末尾,然后回来,需要要删的元素,将链表next指针指向下一个元素即可:

解法三:

class solution {
public:
    listnode* removeelements(listnode* head, int val) {
        if (!head) return null;
        head->next = removeelements(head->next, val);
        return head->val == val ? head->next : head;
    }
};

类似题目:

remove element

delete node in a linked list

参考资料:

https://leetcode.com/problems/remove-linked-list-elements/discuss/57324/ac-java-solution

https://leetcode.com/problems/remove-linked-list-elements/discuss/57331/accepted-7-line-clean-java-solution

到此这篇关于c++实现leetcode(203.移除链表元素)的文章就介绍到这了,更多相关c++实现移除链表元素内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《C++实现LeetCode(203.移除链表元素).doc》

下载本文的Word格式文档,以方便收藏与打印。