Leetcode 203. Remove Linked List Elements
程序员文章站
2024-02-19 08:27:28
...
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
思路:
要移除一个节点,则需要把前一个节点的next指向当前被移除节点的next,因此需要一个pre节点。
被移除的节点可能是head节点,因此需要一个指向head的节点。
public ListNode removeElements(ListNode head, int val) {
if (head == null) {
return null;
}
ListNode root = new ListNode(0);
root.next = head;
ListNode pre = root;
ListNode dummy = head;
while (dummy != null) {
if (dummy.val == val) {
pre.next = dummy.next;
} else {
pre = pre.next;
}
dummy = dummy.next;
}
return root.next;
}
推荐阅读
-
leetcode 203. Remove Linked List Elements
-
203. Remove Linked List Elements
-
Leetcode 203. Remove Linked List Elements
-
203. Remove Linked List Elements
-
【leetcode】203. Remove Linked List Elements
-
LeetCode笔记:237. Delete Node in a Linked List
-
LeetCode 237. Delete Node in a Linked List
-
Leetcode--Reverse Linked List
-
【LeetCode OJ 328】Odd Even Linked List
-
leetcode 328. Odd Even Linked List