给出一个升序排序的链表,删除链表中的所有重复出现的元素,只保留原链表中只出现一次的元素。
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates (ListNode head) {
// write code here
if(head==null||head.next==null){
return head;
}
ListNode preHead =new ListNode(0);
preHead.next=head;
ListNode pre=preHead;
ListNode cur=preHead.next;
while(cur!=null&& cur.next!=null){
if(cur.val==cur.next.val){
ListNode temp=cur.next;
while(temp!=null&& temp.val==cur.val){
temp=temp.next;
}
cur=temp;
}else{
pre.next=cur;
pre=pre.next;
cur=cur.next;
}
}
pre.next=cur;
return preHead.next;
}
}