您的位置:首页 > 其它

LeeCode-Remove Duplicates from Sorted List

2016-04-25 18:55 344 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: