当前位置:网站首页>203、移出链表元素(链表)
203、移出链表元素(链表)
2022-04-23 10:12:00 【Popuessing's Jersey】
题意:删除链表中等于给定值 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
输出:[]
方法一:使用哨兵节点
public class Yichulianbiaoyuansu {
static class ListNode<E>{
ListNode next; // 对象引用下一个节点对象
E val;//数据:节点数据
ListNode(E val){
this.val = val;
}
}
public ListNode removeElements(ListNode head,int val){
//如果头结点为空,返回空
if(head==null){
return null;
}
//定义哨兵节点
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
ListNode cur = head;
while (cur!=null){
//如果当前节点是要删除的节点
if ((int)cur.val==val){
ListNode node = cur.next;//保存cur当前节点的后一个节点
cur.next = null;//释放当前节点指向的空间(在java中这一步可以省略,由JVM垃圾回收处理内存空间的释放)
pre.next = node;
}else {
pre = cur;
}
cur = cur.next;
}
return dummy.next;
}
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(4);
ListNode node3 = new ListNode(2);
ListNode node4 = new ListNode(4);
node1.next = node2;
node2.next = node3;
node3.next = node4;
Yichulianbiaoyuansu yichulianbiaoyuansu = new Yichulianbiaoyuansu();
ListNode res =yichulianbiaoyuansu.removeElements(node1,1);
//创建链表节点
while (res!=null){
if(res.next==null){
System.out.print(res.val);
}else {
System.out.print(res.val + "->");
}
res = res.next;
}
}
}
版权声明
本文为[Popuessing's Jersey]所创,转载请带上原文链接,感谢
https://blog.csdn.net/CoCo629vanilla/article/details/121388096
边栏推荐
- Chapter 3 enable and adjust the size of IM column storage (im-3.1)
- Sim Api User Guide(4)
- 正大国际讲解道琼斯工业指数到底是什么?
- Using multithreading to output abc10 times in sequence
- 【省选联考 2022 D2T1】卡牌(状态压缩 DP,FWT卷积)
- Chapter 1 Oracle database in memory related concepts (im-1.1)
- 0704、ansible----01
- Configuration of LNMP
- JUC concurrent programming 07 -- is fair lock really fair (source code analysis)
- Career planning and implementation in the era of meta universe
猜你喜欢
随机推荐
Juc并发编程09——Condition实现源码分析
Yarn核心参数配置
failureForwardUrl与failureUrl
C language: expression evaluation (integer promotion, arithmetic conversion...)
第二章 In-Memory 体系结构 (IM-2.2)
Go language practice mode - functional options pattern
杰理之有时候发现内存被篡改,但是没有造成异常,应该如何查找?【篇】
Windows安装redis并将redis设置成服务开机自启
Leetcode22:括号生成
中职网络安全2022国赛之CVE-2019-0708漏洞利用
SQL tuning series - SQL performance methodology
142、环形链表||
Classic routine: DP problem of a kind of string counting
Longest common front string
Yarn资源调度器
JVM——》常用命令
杰理之用户如何最简单的处理事件【篇】
Using multithreading to output abc10 times in sequence
解决VMware卸载后再安装出现的问题
DBA common SQL statements (5) - latch related