NC24 删除有序链表中重复的元素-II
描述
给出一个升序排序的链表,删除链表中的所有重复出现的元素,只保留原链表中只出现一次的元素。
例如:
给出的链表为1 \to 2\to 3\to 3\to 4\to 4\to51→2→3→3→4→4→5, 返回1\to 2\to51→2→5.
给出的链表为1\to1 \to 1\to 2 \to 31→1→1→2→3, 返回2\to 32→3.
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
if(head == null || head.next == null){
return head ;
}
ListNode dummy = new ListNode(0) ;
ListNode tail = dummy ;
int curt = -1 ;
//Set<Integer> set = new HashSet<>();
while(head != null){
// set.add(head.val);
if(tail.val != head.val && head.val != head.next.val && head.val != curt){
tail.next = new ListNode(head.val) ;
tail = tail.next ;
}
curt = head.val ;
head = head.next ;
if(head.next == null){
if(head.val != curt){
tail.next = new ListNode(head.val) ; ;
}
break ;
}
}
return dummy.next ;
}
}