Given a sorted linked list, delete all duplicates such that each element appear only once.
Example
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
public class Solution {
/**
* @param ListNode head is the head of the linked list
* @return: ListNode head of linked list
*/
public static ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
ListNode prev = head;
ListNode cur = head.next;
while(cur != null) {
if(cur.val == prev.val) cur = cur.next;
else {
prev.next = cur;
prev = prev.next;
cur = cur.next;
}
}
prev.next = cur;//init the pointer of last node.
return head;
}
}