给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。

示例 1:

输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:

输入: 1->1->1->2->3
输出: 2->3

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 1 public class _82 {
 2     public ListNode deleteDuplicates(ListNode head) {
 3         if (head == null || head.next == null) return head; // 有0个或1个节点
 4         if (head.next.next == null && head.val == head.next.val) return null; // 有2个值相同节点
 5         ListNode p = head, q = p.next;
 6         List<ListNode> noRepeat = new ArrayList<>();
 7         if (p.val != q.val) {
 8             noRepeat.add(p);
 9         }
10         // 扫一遍将不重复的数字记录下来
11         while (q != null){
12             if (p.val != q.val && q.next != null && q.val != q.next.val)
13                 noRepeat.add(q);
14             if (q.next == null && p.val != q.val){
15                 noRepeat.add(q);
16             }
17             p = p.next;
18             q = p.next;
19         }
20         for (int i = 0; i < noRepeat.size()-1; i++){
21             noRepeat.get(i).next = noRepeat.get(i+1);
22         }
23         if (noRepeat.size() <= 0)
24             return null;
25         noRepeat.get(noRepeat.size()-1).next = null;
26         return noRepeat.get(0);
27     }
28
29     public static ListNode create(int[] elems){
30         if (elems == null) return null;
31         ListNode head = new ListNode(-1);
32         ListNode p = head;
33         for (int e : elems){
34             ListNode listNode = new ListNode(e);
35             listNode.next = null;
36             p.next = listNode;
37             p = p.next;
38         }
39         return head.next;
40     }
41
42     public static void main(String[] args) {
43         int[] elems = {1,1,1,2,2,3,3,4,5,6,7};
44         ListNode head = create(elems);
45         ListNode listNode = new _82().deleteDuplicates(head);
46         System.out.println();
47         while (listNode != null) {
48             System.out.print(listNode.val+", ");
49             listNode = listNode.next;
50         }
51     }
52 }
02-11 11:41