203. Remove Linked List Elements - Easy

前往題目

想法

  • 直覺的操作,單純刪除node

思路

  1. 循環直到cur.nextnull
  2. 如果next的值等於目標值那就把next賦值為next.next
  3. 否則移動當前指針到下一個

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/
作者
Simon Lai
發布於
2024年10月10日
許可協議