Problem:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
思路:
采用递归的思想,如果当前节点与下个节点的值不相同,则当前节点的下一个节点就是以下一个节点为头结点进行递归删除后的链表;如果值相等,则都舍去,直接返回以下下个节点为头结点进行递归删除后的链表。
Solution:
ListNode* deleteDuplicates(ListNode* head) {
if (!head) return NULL;
if (!head->next) return head;
int val = head->val;
ListNode* p = head->next;
if (p->val != val) {
head->next = deleteDuplicates(p);
return head;
} else {
while (p && p->val == val) p = p->next;
return deleteDuplicates(p);
}
}
性能:
Runtime: 12 ms Memory Usage: 9.6 MB