import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode deleteDuplicates (ListNode head) { // write code here // 解题思路: // 如果一个节点和它的前一个节点及后一个节点都不相同,则把该节点加入到不重复链表中 // 然后把当前节点作为前一个节点并且当前节点后移动,重复上述比较操作 // 最后记得清空不重复链表中最后一个元素的next if (head == null || head.next == null) { return head; } ListNode root = new ListNode(-2); ListNode rPre = root; ListNode pre = new ListNode(-1); ListNode next = null; while (head != null) { next = head.next; int nextVal = (next == null) ?-100:next.val; if(pre.val != head.val && head.val != nextVal){ rPre.next = head; rPre = rPre.next; } pre = head; head =head.next; } rPre.next = null; return root.next; } }