当前位置:网站首页>【LeetCode】203.移除链表元素
【LeetCode】203.移除链表元素
2022-07-31 10:03:00 【酥酥~】
题目
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
示例 2:
输入:head = [], val = 1
输出:[]
示例 3:
输入:head = [7,7,7,7], val = 7
输出:[]
提示:
列表中的节点数目在范围 [0, 104] 内
1 <= Node.val <= 50
0 <= val <= 50
题解
循环遍历
/** * 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* result = new ListNode(0,head);
ListNode* temp = result;
while(temp->next != NULL)
{
if(temp->next->val == val)
temp->next = temp->next->next;
else
temp = temp->next;
}
return result->next;
}
};
使用递归
/** * 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) {
if(head == nullptr)
return nullptr;
head->next = removeElements(head->next,val);
return head->val != val ? head : head->next;
}
};
边栏推荐
猜你喜欢
随机推荐
js部门预算和支出雷达图
Echart饼图添加轮播效果
LeetCode二叉树系列——101.对称二叉树
Chapter Six
matlab 读取csv文件绘图
解决rpc error: code = Unimplemented desc = method CheckLicense not implemented
如何将虚拟机上的文件复制到主机上
(C语言)程序环境和预处理
Browser usage ratio js radar chart
js department budget and expenditure radar chart
js空气质量aqi雷达图分析
一些计时软件,生产力工具
win10镜像下载
[ verb phrase ] collection
Come n times with the sword--05. Replace spaces
Kotlin—基本语法 (五)
Chapter VII
Business-(Course-Chapter-Subsection) + Course Publishing Some Business Ideas
A Spark SQL online problem troubleshooting and positioning
Use turtle to draw buttons
![[NLP] Interpretation of Transformer Theory](/img/5f/8e1b9e48310817a0443eb445479045.png)








