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
.
一、算法分析
处理不带头结点的单链表,涉及到删除的时候需要考虑删除的是不是头结点;并且需要考虑头结点为空时的情况;
二、C语言实现
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* deleteDuplicates(struct ListNode* head) { struct ListNode *pre,*p; if(head==NULL){ return head; } while(head!=NULL && head->next!=NULL && head->next->val==head->val){ head=head->next; } pre=head; p=head->next; while(p){ if(p->val==pre->val){ pre->next=p->next; p=p->next; }else{ pre=p; p=p->next; } } return head; }