Firstly, see my ugly code!
/**
* 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 null;
ListNode curr = head;
while (curr != null && curr.next != null){
if (curr.val == curr.next.val && curr.next.next != null) {
curr.next = curr.next.next;
// the 'continue' solve the problem that "11111" etc.
continue;
}
else if (curr.val == curr.next.val && curr.next.next == null) {
curr.next = null;
}
curr = curr.next;
}
return head;
}
}
Recursive Solution(Excellent idea)\
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)return head;
head.next = deleteDuplicates(head.next);
return head.val == head.next.val ? head.next : head;
}