LeetCode 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         }
17         ListNode start = new ListNode(head.val - 1);
18         ListNode temp=start;
19         ListNode curr=head;
20         int prev=start.val;
21         int next=head.next.val;
22         while (curr.next != null) {
23             if (curr.val != prev && curr.val != curr.next.val) {
24                 prev = curr.val;
25                 temp.next = curr;
26                 temp=temp.next;
27                 curr = curr.next;
28             } else {
29                 prev=curr.val;
30                 curr=curr.next;
31                 if(curr.next!=null) next=curr.next.val;
32             }
33         }
34         if (curr.val != prev) {
35             temp.next = curr;
36         }else temp.next=null;
37         return start.next;
38         
39     }
40 }
原文地址:https://www.cnblogs.com/birdhack/p/4209595.html