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
.
题意:删除有序链表中出现重复值的结点。
思路:采用双指针p和pPre,然后开始遍历,判断p.val和p.next.val是否相等,不相等pPre=p;p=p.next,否则,接着向下查找,找到不等于p.val的结点,然后将pPre.next赋值为p,接着进行删除。同时,要判断第一个相等的值是否为头结点,如果是,将head的值直接指向p。
代码:
public ListNode deleteDuplicates(ListNode head) { if(head==null||head.next==null){ return head; } ListNode p = head; ListNode pPre = null; while(p!=null&&p.next!=null){ if(p.val !=p.next.val){ pPre = p; p = p.next; }else{ int val = p.val; while(p!=null&&p.val==val){ p=p.next; } if(pPre==null){ head = p; }else{ pPre.next = p; } } } return head; }