Remove Duplicates from Sorted List II

Link: http://oj.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.

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode deleteDuplicates(ListNode head) {
14         if (head == null || head.next == null)
15             return head;
16         ListNode result = new ListNode(0);
17         ListNode r = result;
18         ListNode p1 = head;
19         ListNode p2 = head;
20         
21         while (p2 != null) {
22             int times = 0;
23             while (p2 != null && p1.val == p2.val){
24                 times++;
25                 p2 = p2.next;
26             }
27             if(times == 1)
28             {
29                 result.next = p1;
30                 result = result.next;
31             }
32             p1 = p2;
33         }
34         result.next = null;
35         return r.next;
36     }
37 }
原文地址:https://www.cnblogs.com/Altaszzz/p/3703600.html