remove-duplicates-from-sorted-list-ii

来源:互联网 发布:医学听诊软件 编辑:程序博客网 时间:2024/05/22 15:44

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.

感觉有点难,递归的方法还是半懂半不懂的。。

代码:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *deleteDuplicates(ListNode *head) {        if(head==NULL || head->next==NULL)            return head;        int val = head->val;        ListNode *p = head->next;        if(val!=p->val){            head->next = deleteDuplicates(p);            return head;        }        else{            while(p!=NULL && p->val==val)                p = p->next;            return deleteDuplicates(p);        }    }};