83. Remove Duplicates from Sorted List - Easy
前往題目
想法
- 簡單的去元素操作
思路
想得有點太複雜,原本還想把去掉的元素的next
也改成null
,網友的解法並沒有這樣做,不知道gc
會不會回收
- 循環直到
cur.next
為null
- 兩兩比較,如果數值一樣,就更改
next
為下一個,但不要移動當前的node
,除非數值不同再移動
Code
class Solution {
public ListNode deleteDuplicates(ListNode head) {
// Base case
if (head == null || head.next == null) return head;
ListNode cur = head;
while (cur.next != null) {
// Current compare with the next
if (cur.val == cur.next.val) {
// Change "next", but no need to move "cur" yet
cur.next = cur.next.next;
} else {
// Acutally move cur
cur = cur.next;
}
}
return head;
}
}
83. Remove Duplicates from Sorted List - Easy
https://f88083.github.io/2024/10/08/83-Remove-Duplicates-from-Sorted-List-Easy/