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
.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head)
{
if(head==NULL)
return NULL;
if(head!=NULL&&head->next==NULL)
return head;
if(head->next->next==NULL)
{
if(head->val==head->next->val)
{
head->next==NULL;
return head->next;
}
if(head->val!=head->next->val)
{
return head;
}
}
struct ListNode* p;
p=head;
int count=0;
while(p!=NULL)
{
p=p->next;
count++;
}
int *array;
array=(int *)malloc(count*sizeof(int));
p=head;
int i=0;
while(p!=NULL)
{
array[i]=p->val;
i++;
p=p->next;
}
p=head;
for(i=0;i<count-1;i++)
{
if(array[i]!=array[i+1])
{
p->val= array[i];
p=p->next;
}
}
p->val=array[count-1];
p->next=NULL;
return head;
}