1 public class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 if(head==null || head.next==null) 4 return head; 5 ListNode safe = new ListNode(-1); 6 ListNode pre = head; 7 ListNode cur = safe; 8 while(pre!=null){ 9 boolean dul = false; 10 while(pre.next!=null && pre.val == pre.next.val){ 11 pre = pre.next; 12 dul = true; 13 } 14 if(dul){ 15 pre = pre.next; 16 continue; 17 } 18 cur.next = pre; 19 pre = pre.next; 20 cur = cur.next; 21 } 22 cur.next = null; //because {1,1} 23 return safe.next; 24 } 25 }
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
.