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.
用《剑指offer》的“删除链表中某个节点”的方法来做这道题即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null){
return head;
}else if(head.next==null){
return head;
}
ListNode temp=head;
ListNode next=head.next;
while(next.next!=null){
if(head.val==next.val){
next.val=next.next.val;
next.next=next.next.next;
}else{
head=head.next;
next=next.next;
}
}
if(head.val==next.val){
head.next=null;
}
return temp;
}
}