当前位置:网站首页>【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;
}
};
边栏推荐
- 第二十三课,抗锯齿(Anti Aliasing)
- js radar chart statistical chart plugin
- Come n times - 09. Implement queues with two stacks
- ARC在编译和运行做了什么?
- postgresql generate random date, random time
- js空气质量aqi雷达图分析
- canvas粒子变幻各种形状js特效
- Emotional crisis, my friend's online dating girlfriend wants to break up with him, ask me what to do
- 出色的移动端用户验证
- 浏览器使用占比js雷达图
猜你喜欢
随机推荐
Mybaits Frequently Asked Questions Explained
实现线程池
spark过滤器
Chapter VII
js implements the 2020 New Year's Day countdown bulletin board
NowCoderTOP28-34 binary tree - continuous update ing
loadrunner-controller-场景执行run
js滚动条滚动到指定元素
学习笔记——七周成为数据分析师《第二周:业务》:业务分析框架
比较并交换 (CAS) 原理
loadrunner脚本--添加检查点
centos7安装mysql5.7
数字加分隔符
可以用聚酯树脂将接线板密封接线盒吗?(接线盒灌封胶用哪种树脂)
Kotlin入门介绍篇
Come n times - 07. Rebuild the binary tree
ARC在编译和运行做了什么?
js department budget and expenditure radar chart
Come n times with the sword--05. Replace spaces
GZIPInputStream 类源码分析









