Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
題意:83題的followup,這次重復的元素一個都不保留了。
思路:問題的關鍵是如果判斷一個元素是不是非重復元素,判斷的條件就是它不和前面的元素相等也不和后面的元素相等。由于是鏈表,我們需要用一個變量記錄前面的listnode,才能判斷。還有一點需要注意的就是頭尾節點是沒有pre和next的,注意pre和next是否是null的判斷。
所以本題需要三個指針,dummy指向已連接起來的符合條件的節點,cur指向當前遍歷到的節點,pre指向cur前面一個節點,每遍歷到一個節點,如果它和前后都不相等,就把dummy.next指向它,然后把dummy更新為dummy.next。
public ListNode deleteDuplicates(ListNode head) {
ListNode res = new ListNode(0);
if (head == null || head.next == null) {
return head;
}
ListNode dummy = res;
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
if ((pre != null && cur.next != null && cur.val != pre.val && cur.val != cur.next.val)
|| (pre == null && cur.next != null && cur.val != cur.next.val)
|| (cur.next == null && cur.val != pre.val)) {
dummy.next = cur;
dummy = dummy.next;
}
pre = cur;
cur = cur.next;
}
dummy.next = null;
return res.next;
}
bug:最后又疏忽了要把dummy.next指向null,不然1,2,3,3這種case就會fail。