给定一个排序链表,删除所有重复的元素每个元素只留下一个。
样例
给出 1->1->2->null
,返回 1->2->null
给出 1->1->2->3->3->null
,返回 1->2->3->null
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /* * @param head: head is the head of the linked list * @return: head of linked list */ ListNode * deleteDuplicates(ListNode * head) { // write your code here if(head==NULL) return 0; ListNode *p=head; ListNode *next; while(p->next!=NULL) { next=p->next; if(next->val==p->val) { p->next=next->next; delete(next); }else//else很重要 { p=p->next; } } return head; } };