码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ:Remove Duplicates from Sorted List II(链表去重II)

时间:2016-01-14 22:18:45      阅读:197      评论: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.

这里对于链表去重是要将有重复的链表节点全部都去掉,一个都不能留,思路还是比较简单的,跟前面的I那一题实际上差不多,代码如下所示:

 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) return NULL;
13         ListNode * helper = new ListNode(INT_MAX);
14         helper->next = head;
15         ListNode * prev = helper;
16         ListNode * curr = head;
17         while(curr){
18             if(curr->next && curr->val == curr->next->val){
19                 ListNode * tmpNode = curr->next;
20                 while(tmpNode->next && curr->val == tmpNode->next->val){
21                     tmpNode = tmpNode->next;
22                 }
23                 prev->next = tmpNode->next;
24                 curr = prev->next;
25             }else{
26                 prev = curr;
27                 curr = curr->next;
28             }
29         }
30         return helper->next;
31     }
32 };

 

LeetCode OJ:Remove Duplicates from Sorted List II(链表去重II)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/5005052.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!