首页 > 其他 > 详细

[LeetCode]Remove Duplicates from Sorted List II

时间:2015-10-26 18:45:58      阅读:255      评论:0      收藏:0      [点我收藏+]

题目描述:(链接)

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!