标签:
题目描述:(链接)
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
解题思路:
递归版:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* deleteDuplicates(ListNode* head) { 12 if (!head || !(head->next)) return head; 13 14 ListNode *p = head->next; 15 if (head->val == p->val) { 16 while (p && head->val == p->val) { 17 ListNode *tmp = p; 18 p = p->next; 19 delete tmp; 20 } 21 delete head; 22 return deleteDuplicates(p); 23 } else { 24 head->next = deleteDuplicates(head->next); 25 return head; 26 } 27 } 28 };
迭代版:
待续
[LeetCode]Remove Duplicates from Sorted List II
标签:
原文地址:http://www.cnblogs.com/skycore/p/4911929.html