[Leetcode] 82. Remove Duplicates from Sorted List II sorted linked to weight (light to heavy deleted)

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5

Example 2:

Input: 1->1->1->2->3
Output: 2->3

 

The meaning of problems

Given an ordered list, where there are duplicate elements who deleted light

 

Thinking

 

Code

 1 class Solution {
 2      public ListNode deleteDuplicates(ListNode head) {
 3        if (head == null || head.next == null)  return head;
 4          
 5         ListNode dummy = new ListNode(-1);
 6         dummy.next = head;
 7         ListNode pre = dummy;
 8          
 9         while (pre.next != null) {
10             ListNode cur = pre.next;
11             while (cur.next != null && cur.val == cur.next.val) {
12                 cur = cur.next;
13             }
14             if (cur != pre.next) {
15                 pre.next = cur.next;
16             } else {
17                 pre = pre.next;
18             }
19         }
20         
21         return dummy.next;
22     }
23 }

 

Guess you like

Origin www.cnblogs.com/liuliu5151/p/10955489.html