您的位置:首页 > 其它

Remove Duplicates from Sorted List II [LeetCode]

2013-11-11 10:26 387 查看
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
.

Solution:

ListNode *deleteDuplicates(ListNode *head) {
if(head == NULL || head->next == NULL)
return head;

//remove the head
ListNode * same_node = NULL;
while(head != NULL) {
if(same_node == NULL) {
if(head->next != NULL && head->val == head->next->val){
same_node = head;
head = head->next;
}else {
break;
}
}else {
if(head->val == same_node->val)
head = head->next;
else
same_node = NULL;
}
}

if(head == NULL || head->next == NULL)
return head;

ListNode * pre = head;
ListNode * same = NULL;
ListNode * current = pre->next;
while(current != NULL) {
if(same == NULL) {
if(current->next != NULL && current->val == current->next->val){
same = current;
pre->next = current->next;
}else{
pre = pre->next;
}
current = current->next;
}else {
if(current->val == same->val){
pre->next = current->next;
current = current->next;
}else {
same = NULL;
}
}
}

return head;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: