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
.
Analysis:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode pre=newHead, cur=head, nex=head.next;
while(nex != null) {
if(cur.val == nex.val) {
nex = nex.next;
while(nex!=null && nex.val==cur.val) {
nex = nex.next;
}
pre.next = nex;
cur = nex;
if(nex!=null) nex=nex.next;
}
else {
pre = cur;
cur = nex;
nex = nex.next;
}
}
return newHead.next;
}
}