[Linked List]Remove Duplicates from Sorted List II

Total Accepted: 59433 Total Submissions: 230628 Difficulty: Medium

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* help_node = new ListNode();
help_node->next = head; ListNode* cur_pre = help_node;
ListNode* cur = head; while(cur!=NULL){
ListNode* p = cur->next;
while(p!=NULL && p->val==cur->val){
p = p->next;
} if(p != cur->next){
while(cur != p) {
ListNode* tmp = cur;
cur = cur->next;
delete (tmp);
} cur_pre->next = p;
cur = p;
}else{
cur_pre = cur;
cur = cur->next;
}
} head = help_node->next;
delete (help_node);
return head;
}
};
上一篇:java scoket (UDP通信模型)简易聊天室


下一篇:iOS学习笔记——AutoLayout的约束