LeetCode 82. Remove Duplicates from Sorted List II

原题链接在这里:https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

题目:

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.

题解:

类似Remove Duplicates from Sorted List不同就是要完全去掉duplicate.

当cur.next.val == cur.next.next.val 时,就一直移动dup = cur.next.next直到cur.next.val != dup.val. 然后cur的next指向dup.

Time Complexity: O(n), n 是list长度.

Space: O(1).

AC Java:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 class Solution {
10     public ListNode deleteDuplicates(ListNode head) {
11         if(head == null || head.next == null){
12             return head;
13         }
14         
15         ListNode dummy = new ListNode(0);
16         dummy.next = head;
17         ListNode cur = dummy;
18         while(cur.next != null && cur.next.next != null){
19             if(cur.next.val != cur.next.next.val){
20                 cur = cur.next;
21             }else{
22                 ListNode dup = cur.next.next;
23                 while(dup != null && cur.next.val == dup.val){
24                     dup = dup.next;
25                 }
26                 cur.next = dup;
27             }
28         }
29         
30         return dummy.next;
31     }
32 }
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825003.html