Remove Linked List Elements
程序员文章站
2022-04-18 19:23:36
...
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return null;
}
ListNode listNode = new ListNode(0);
listNode.next = head;
head = listNode;
while (head.next != null) {
if (head.next.val == val) {
head.next = head.next.next;
} else {
head = head.next;
}
}
return listNode.next;
}
}
上一篇: System.gc 没有立即执行
下一篇: List中remove数据
推荐阅读
-
Java基础学习总结(129)——Arrays.asList得到的List进行add和remove等操作出现异常解析
-
Java list.remove( )方法需要注意的地方
-
Python 删除List元素的三种方法remove、pop、del
-
【LeetCode OJ 328】Odd Even Linked List
-
数据结构与算法 —— 链表linked list(04)
-
PTA 02-线性结构3 Reversing Linked List (25 分)
-
PAT-A-1052 Linked List Sorting
-
leetcode 328. Odd Even Linked List
-
leetcode 328. Odd Even Linked List
-
328. Odd Even Linked List