首页 > 其他 > 详细

LeetCode – Refresh – Remove Duplicates from Sorted List II

时间:2015-03-22 17:47:20      阅读:166      评论:0      收藏:0      [点我收藏+]

Notes:

1. Check when the loop finished. The last element still need to be remove.

2. when remove the current one, do not forget to move the pointer back to the prev->next

 

 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         ListNode *result = new ListNode(0);
14         result->next = head;
15         ListNode *prev = result;
16         bool flag = false;
17         while (head) {
18             if (head->next && head->val == head->next->val) {
19                 flag = true;
20                 head->next = head->next->next;
21                 continue;
22             }
23             if (flag) {
24                 prev->next = head->next;
25                 head = prev->next;
26                 flag = false;
27             } else {
28                 prev = head;
29                 head = head->next;
30             }
31         }
32         if (flag) prev->next = prev->next->next;
33         return result->next;
34     }
35 };

 

LeetCode – Refresh – Remove Duplicates from Sorted List II

原文:http://www.cnblogs.com/shuashuashua/p/4357587.html

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