欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > LeetCode203 移除链表元素

LeetCode203 移除链表元素

2024/10/24 20:20:48 来源:https://blog.csdn.net/daishabby2486/article/details/140680944  浏览:    关键词:LeetCode203 移除链表元素

前言

题目: 203.移除链表元素
文档: 代码随想录——移除链表元素
编程语言: C++
解题状态: 解答错误,忘了链表的遍历是如何进行的了

思路

对于链表的操作,最好可以给一个虚拟表头方便操作。另外需要注意的是,在删除链表的节点后,我们需要手动进行清理内存。

代码

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode() : val(0), next(nullptr) {}*     ListNode(int x) : val(x), next(nullptr) {}*     ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* removeElements(ListNode* head, int val) {ListNode* dummyHead = new ListNode(0); // 设置一个虚拟头结点dummyHead -> next = head; // 将虚拟头结点指向head,这样方便后面做删除操作ListNode* cur = dummyHead;while (cur -> next != NULL) {if(cur -> nex t-> val == val) {ListNode* tmp = cur -> next;cur -> next = cur -> next -> next;delete tmp;} else {cur = cur -> next;}}head = dummyHead -> next;delete dummyHead;return head;}
};
  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com