
image.png
思路
- 普通解法. 如果要刪除的節(jié)點就是頭結(jié)點. 就不太好操作, 會多一段先操作頭結(jié)點的代碼
while (head != null && head.val == val) {
head = head.next;
}
ListNode cur = head;
while (cur != null && cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
- 虛擬頭節(jié)點解法. 我們可以新增一個虛擬的頭節(jié)點, dummy.next -> head, 這樣處理頭節(jié)點的情況也和普通節(jié)點一樣了.讓它看起來像是第二個節(jié)點, 注意最后返回結(jié)果的時候也要返回
dummy.next這才是原始的頭結(jié)點
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cur = dummy;
while (cur != null && cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return dummy.next;
}