您的位置:首页 > 其它

[LeetCode] Remove Duplicates from Sorted List II

2014-11-23 14:38 253 查看
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
.

class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
ListNode *ptr = NULL;
ListNode *cur = head;
ListNode *head0 = NULL;
int cnt = 0;
while(cur != NULL){
ListNode *tmp = cur;
while(cur -> next != NULL && cur -> next -> val == cur -> val)
cur = cur -> next;
if(tmp == cur){
cnt ++;
if(cnt == 1) head0 = ptr = cur;
else {
ptr -> next = cur;
ptr = ptr -> next;
}
}
cur = cur -> next;
if(cnt >= 1)
ptr -> next = NULL;//如出现 1 2 2 2 这种情况,所以要把ptr -> next 设为NULL;
}
if(cnt == 0) return NULL;
return head0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: