/**
* Remove Duplicates from Sorted List
*
* Given a sorted linked list, delete all duplicates such that each element
* appear only once.
*
* For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3.
*/
public class S83 {
public static void main(String[] args) {
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(1);
n1.next = n2;
ListNode n3 = new ListNode(2);
n2.next = n3;
ListNode x = deleteDuplicates(n1);
x.print();
}
public static ListNode deleteDuplicates(ListNode head) {
ListNode base = head; // base 为每次被比较的对象
if(head==null || head.next == null){
return head;
}
ListNode cur = head.next; // cur为每次去比较的对象
while(base!=null && cur!=null){
if(base.val == cur.val){ // 重复了就跳过去
base.next = cur.next;
}else{ // 不重复就更新base
base = base.next;
}
cur = cur.next; // 更新cur
}
return head;
}
}