我是靠谱客的博主 无语鼠标,这篇文章主要介绍C++实现LeetCode(203.移除链表元素),现在分享给大家,希望可以做个参考。

[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 @mithmatt for adding this problem and creating all test cases.

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

解法一:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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,更不用删除下一个结点了。最后还要验证头结点是否需要删除,要的话直接返回下一个结点,参见代码如下:

解法二:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
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指针指向下一个元素即可:

解法三:

复制代码
1
2
3
4
5
6
7
8
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/

https://leetcode.com/problems/remove-linked-list-elements/discuss/57324/AC-Java-solution

https://leetcode.com/problems/remove-linked-list-elements/discuss/57306/3-line-recursive-solution

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

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

最后

以上就是无语鼠标最近收集整理的关于C++实现LeetCode(203.移除链表元素)的全部内容,更多相关C++实现LeetCode(203内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(145)

评论列表共有 0 条评论

立即
投稿
返回
顶部