当前位置:网站首页>203. Remove linked list elements (linked list)
203. Remove linked list elements (linked list)
2022-04-23 10:15:00 【Popuessing's Jersey】
The question : Delete the given value in the list val All nodes of .
Example 1:
Input :head = [1,2,6,3,4,5,6], val = 6
Output :[1,2,3,4,5]
Example 2:
Input :head = [], val = 1
Output :[]
Example 3:
Input :head = [7,7,7,7], val = 7
Output :[]
Method 1 : Use sentinel nodes
public class Yichulianbiaoyuansu {
static class ListNode<E>{
ListNode next; // Object references the next node object
E val;// data : Node data
ListNode(E val){
this.val = val;
}
}
public ListNode removeElements(ListNode head,int val){
// If the header node is empty , Returns an empty
if(head==null){
return null;
}
// Defining sentinel nodes
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
ListNode cur = head;
while (cur!=null){
// If the current node is the node to be deleted
if ((int)cur.val==val){
ListNode node = cur.next;// preservation cur The next node of the current node
cur.next = null;// Release the space pointed to by the current node ( stay java This step can be omitted , from JVM Garbage collection handles the release of memory space )
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);
// Create a linked list node
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://yzsam.com/2022/04/202204231011141155.html
边栏推荐
猜你喜欢
随机推荐
杰理之有时候发现内存被篡改,但是没有造成异常,应该如何查找?【篇】
通过流式数据集成实现数据价值(1)
Read LSTM (long short term memory)
第三章 启用和调整IM列存储的大小(IM-3.1)
Can Jerry's AES 256bit [chapter]
一文读懂PlatoFarm新经济模型以及生态进展
Sim Api User Guide(4)
Go language practice mode - functional options pattern
Function realization of printing page
第二章 In-Memory 体系结构 (IM-2.2)
Arm debugging (1): two methods to redirect printf to serial port in keil
209、长度最小的子数组(数组)
Shell script interaction free
C language: expression evaluation (integer promotion, arithmetic conversion...)
ansible playbook语法和格式 自动化云计算
707、设计链表(链表)
What about Jerry's stack overflow? [chapter]
C语言——自定义类型
Operation of 2022 tea artist (primary) test question simulation test platform
Chapter 1 Oracle database in memory related concepts (im-1.1)