struct ListNode* deleteDuplicates(struct ListNode* head ) {
// write code here
if(head==NULL||head->next==NULL)
return head;
struct ListNode *p;
p=head->next;
while(head->val==p->val)
{
head=head->next;
p=head->next;
}
return head;
}
一个有序链表从小到大排序,删除其中的重复元素并返回表头,
为什么当链表的各元素一样时输出错误,比如链表是{1,1,1}
修改如下,供参考:
// 将线性表中重复的元素删除,head非递减有序
struct ListNode* deleteDuplicates(struct ListNode* head)
{
if (head == NULL || head->next == NULL)
return head;
struct ListNode* p = NULL, *r = NULL;
p = head;
while ( p && p->next )
{
if (p->val == p->next->val){
r = p->next;
p->next = r->next;
free(r);
}
else
p = p->next;
}
return head;
}