题目如下:
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.
分析如下:
和前一道题目很类似。不同的是,这道题目删除的元素更多。写了比较长时间。因为想清楚一些细节花了比较长时间,比如新生成的list的head为空时和head不为空时,处理方式是不同的。看了答案发现了一个非常巧妙的办法可以避免考虑这个问题,使用递归。
我的代码:
// 96ms过大集合
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head==NULL||head->next==NULL)
return head;
if((head!=NULL)&&(head->next!=NULL)&&(head->val==head->next->val)&&(head->next->next==NULL) )
return NULL;
else if((head!=NULL)&&(head->next!=NULL)&&(head->val!=head->next->val)&&(head->next->next==NULL))
return head;
ListNode* r=head; //前一个
ListNode* p=head->next; //后二个
ListNode* new_tail=NULL;
ListNode* new_head=NULL;
int flag=0;
while(p!=NULL){
flag=0;
while(p!=NULL&&p->val==r->val){
p=p->next;
flag=1;
}
if((flag==0)&&(new_head==NULL)){
new_head=r;
new_tail=r;
}else if((flag==0)&&(new_head!=NULL)){
new_tail->next=r;
new_tail=r;
}
r=p;
if(p!=NULL){
p=p->next;
}
}
if(r!=NULL&&p==NULL) {
if(new_head==NULL){
new_head=r;
new_tail=r;
}else if(new_head!=NULL){
new_tail->next=r;
new_tail=r;
}
}
if(new_tail!=NULL)
new_tail->next=NULL;
return new_head;
}
};
优秀代码如下:
//使用递归,28ms过大集合
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates2(ListNode *head) {
if(!head||!head->next)return head;
ListNode *p=head->next;
if(head->val==p->val)
{
while(head->val==p->val)
{
p=p->next;
if(!p)break;
}
return deleteDuplicates(p);
}
head->next=deleteDuplicates(head->next);
return head;
}
};
参考资料:
(1) http://discuss.leetcode.com/questions/257/remove-duplicates-from-sorted-list-ii
update:
2015-01-10
1 没有使用递归
2 设置了dummy head简化代码
//22ms
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if (head == NULL || head->next == NULL) return head;
ListNode* dummy_head = new ListNode(-1);
ListNode* tail = dummy_head;
ListNode* node1 = head;
ListNode* node2 = head->next;
while (node1 != NULL && node2 != NULL ) {
if (node1->val != node2->val) {
tail->next = node1;
tail = tail->next;
node1 = node2;
node2 = node2->next;
} else {
while(node1!= NULL && node1->val == node2->val) {
node1 = node1->next;
}
if (node1 != NULL) {
node2 = node1->next;
}
}
}
if (node1!= NULL && tail->val != node1->val) {
tail->next = node1;
tail = tail->next;
}
tail->next = NULL;
return dummy_head->next;
}
};