Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given
Given
Given
1->2->3->3->4->4->5
, return 1->2->5
.Given
1->1->1->2->3
, return 2->3
.
Solution 1: Use dummy node for deleting.
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode i=dummy;
while (i.next!=null && i.next.next!=null) {
if (i.next.val!=i.next.next.val) i=i.next;
else {
ListNode j=i.next;
while (j.next!=null && j.val==j.next.val) j=j.next;
i.next=j.next;
}
}
return dummy.next;
}
}
没有评论:
发表评论