三个指针 pre 指向当前节点的前一个 right指向重复元素的下一个元素 cur指向重复元素的头一个。
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @return ListNode类 */ public ListNode deleteDuplicates (ListNode head) { if(head == null) return null; ListNode phead = new ListNode(-1); phead.next = head; ListNode cur = head; ListNode right = head.next; ListNode pre = phead; while(cur.next != null ){ if(cur.val == right.val){ while(right != null && cur.val == right.val ) {right = right.next;} pre.next = right; }else{ pre = cur; } if(right == null) break; cur = right; right = cur.next; } return phead.next; } }