Leecode no.82 刪除排序連結串列中的重複元素 II
阿新 • • 發佈:2021-12-21
package leecode;
/**
* 82. 刪除排序連結串列中的重複元素 II
*
* 存在一個按升序排列的連結串列,給你這個連結串列的頭節點 head ,請你刪除連結串列中所有存在數字重複情況的節點,只保留原始連結串列中沒有重複出現的數字。
*
* 返回同樣按升序排列的結果連結串列。
*
* @author Tang
* @date 2021/12/21
*/
public class DeleteDuplicates2 {
/**
* 存一個value 儲存的是上一個該刪除的元素值
*
*
* @param head
* @return
*/
public ListNode deleteDuplicates(ListNode head) {
if(head == null) {
return null;
}
ListNode first = new ListNode();
first.next = head;
int value = Integer.MIN_VALUE;
ListNode temp = first;
while (head.next != null) {
if(head.val == head.next.val || head.val == value) {
//記錄下這個重複的值
value = head.val;
//刪掉head
temp.next = head.next;
} else {
temp = temp.next;
}
head = head.next;
}
if(head.val == value) {
temp.next = null;
}
return first.next;
}
public static void main(String[] args) {
}
}