LeetCode 82 Remove Duplicates from Sorted List II

Here, I used a helper function to help me get the tail node of duplicate number list.

Store the prev and tail node.

cur.next != null && cur.next.next != null.

简洁版代码:

 1 //          1    2    3    3    3    3    3    3    3    3    3    4    5    6 NULL
 2 // dummy        cur
 3 
 4 public ListNode removeDeplicatesII(ListNode head) {
 5 if (head == null || head.next == null) {
 6 return head;
 7 }
 8         ListNode dummy = new ListNode(0);
 9         dummy.next = head;
10         ListNode cur = dummy;
11         ListNode prev = null, tail = null;
12         
13   // For example : 1 -> 1 -> null, 
14   // if cur.next == null, then if we use cur.next.next, then it will come out NPE.
15   // for this example, after we delete 1, then we have dummy -> null. So if we don't consider about 
16   // the situation of cur.next != null , then it will come out an NPE exception.
17         while (cur.next != null && cur.next.next != null) {
18             if (cur.next.val == cur.next.next.val) {
19                 prev = cur;
20                 tail = getTailNode(cur.next);
21                 prev.next = tail.next;
22             } else {
23                 cur = cur.next;
24             }
25         }
26         return dummy.next;
27     }
28 
29     // Here we used an heler function to get the tail node.
30     public ListNode getTailNode(ListNode node) {
31         while (node  != null && node.next != null) {
32             if (node.val == node.next.val) {
33                 node= node.next;
34             } else {
35                 break;
36             }
37         }
38         return node;
39     }

shi一样的代码1:

 1 public class Solution {
 2   public ListNode removeDup(ListNode head) {
 3     // Write your solution here
 4     if (head == null) {
 5          return head; 
 6     }
 7     ListNode dummy = new ListNode(0);
 8     ListNode prev = dummy;
 9     dummy.next = head;
10     ListNode cur = head;
11     while (cur != null && cur.next != null) {
12          if (cur.value == cur.next.value) {
13            ListNode newHead = remove(cur);
14         prev.next = newHead;
15         cur = newHead;
16       } else {
17         prev = cur;
18         cur = cur.next;
19       }
20     }
21     return dummy.next;
22   }
23   private ListNode remove(ListNode head) {
24     if (head == null) {
25      return head; 
26     }
27     while (head.next != null && head.value == head.next.value) {
28           head = head.next;
29     }
30     // head.value != head.next.value.
31     return head.next;
32   }
33 }
原文地址:https://www.cnblogs.com/mayinmiao/p/8491376.html