本題中,我們是要移除鏈表的某一個節點,為了確保統一操作,我們需要使用虛擬頭節點,這樣我們刪除節點的時候,就是把這個要刪除的節點(當前節點cur)的前一個節點pre,使得pre.next指向要刪除節點的下一個節點,所以就是pre.next = cur.next。
如果不是我們要刪除的節點,那我們就移動pre指針,讓其往后走,就是pre=cur。然后再切換當前節點的位置,cur = cur.next。
public ListNode removeElements(ListNode head, int val) {if (head == null) {return head;}// 因為刪除可能涉及到頭節點,所以設置dummy節點,統一操作ListNode dummy = new ListNode(-1, head);ListNode pre = dummy;ListNode cur = head;while (cur != null) {if (cur.val == val) {pre.next = cur.next;} else {pre = cur;//也可以寫成pre=pre.next}cur = cur.next;}return dummy.next;
}