Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinctnumbers 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
给定一个链表,移除链表中所有重复的元素,仅保留不重复的元素。本题和83题Remove Duplicates from Sorted List的区别是83题保留了重复元素中的一个元素。因此,本题的思路是:
- 遍历链表的节点,若当前节点与下一节点值不等,则递归遍历下一节点;
- 若当前节点与下一节点相等,则下一节点继续移动,直到遇到第一个值不相等的节点,从该节点处继续递归遍历链表。
- 递归的结束条件是当前节点为空或者下一节点为空。
以上便可得到不包含重复元素的新链表,代码记录如下:
/**
* 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(NULL == head || NULL == head->next)
return head;
ListNode *p_next = head->next;
if(p_next->val != head->val)
{
head->next = deleteDuplicates(p_next);
return head;
}
else
{
while(p_next && p_next->val == head->val)
{
p_next = p_next->next;
}
return deleteDuplicates(p_next);
}
}
};