203. Remove Linked List Elements - Easy
前往題目
想法
- 直覺的操作,單純刪除
node
思路
- 循環直到
cur.next為null - 如果
next的值等於目標值那就把next賦值為next.next - 否則移動當前指針到下一個
Code
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null) {
if (cur.next.val == val) {
// Change the next node
cur.next = cur.next.next;
} else { // Actually Move the pointer
cur = cur.next;
}
}
return dummy.next;
}
}203. Remove Linked List Elements - Easy
https://f88083.github.io/2024/10/10/203-Remove-Linked-List-Elements-Easy/