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
.
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode p = head;
ListNode pre = null;
while(p != null){
int t = p.val;
ListNode tp = p;
while(p.next != null && p.next.val == t) p = p.next;
if(tp != p){ //比较节点是否是同一个节点,若不是则删除
if(pre == null) head = p.next;
else pre.next = p.next;
}
else{
pre = p;
}
p = p.next;
}
return head;
}
}