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:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode(0);
ListNode list = dummy;
ListNode pointer= head;
while(pointer != null )
{
if(pointer.next != null && pointer.val == pointer.next.val)
{
int value = pointer.val;
while(pointer!=null && pointer.val == value)
pointer = pointer.next;
}
else
{
list.next = pointer;
list = list.next;
pointer = pointer.next;
}
}
list.next = null;
return dummy.next;
}
}
No comments :
Post a Comment