您的位置:首页 > 其它

Remove Duplicates from Sorted List II

2013-03-22 22:29 274 查看
Remove
Duplicates from Sorted List IIApr
22 '12

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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head == NULL || head->next == NULL) return head;
ListNode prehead(0);
prehead.next = head;
ListNode *q = &prehead,*p = head;
while((p = p->next)!= NULL)
{
if(p->val != q->next->val){
if(p != q->next->next) q->next = p;
else q = q->next;
}else if (p->next==NULL)
q->next = p->next;
}

return prehead.next;
}
};


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