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
.
设置2个指针,cur 和next。
当cur的值与next的值相等时,cur.next= next.next 更新next = next.next;
当cur的值与next的值不等时,cur = next 更新next = next.next;
1 public class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 if(head == null ||head.next == null) return head; 4 ListNode cur = head; 5 ListNode next = head.next; 6 while(next != null){ 7 if(cur.val == next.val) 8 cur.next = next.next; 9 else cur = next; 10 next = next.next; 11 } 12 return head; 13 }