您的位置:首页 > 其它

《leetCode》:Remove Duplicates from Sorted List II

2015-11-24 19:37 411 查看

题目

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.


题目大意:删除一个排序链表中所有出现两次及两次以上的节点。

思路

遍历一次链表,找出链表中只出现了一次的节点,连接起来即可

实现代码如下:

struct ListNode* deleteDuplicates(struct ListNode* head) {
if(head==NULL){//有效性检查
return NULL;
}
struct ListNode* cur=head;
struct ListNode* pre=NULL;//用来记录当前结点的值
struct ListNode* next=NULL;
int count=1;
while(cur->next!=NULL){
next=cur->next;
if(cur->val==next->val){
count++;
}
else if(cur->val!=next->val){
if(count<2){//即cur指针所指向的节点就是只出现了一次的节点
if(pre!=NULL){//说明
pre->next=cur;
pre=cur;
}
else{//此时pre为NULL,说明cur所指向的节点为第一个出现一次的节点
pre=cur;
head=pre;
}
count=1;
}
else{//仅仅将count=1即可
count=1;
}
}
cur=next;
}
if(count==1&&pre==NULL){//只有1个节点的情况或者是出现类似1 1 2这种情况
return cur;
}
else if(count>1&&pre==NULL){//有多个相同的节点的情况
return NULL;
}
else if(count==1&&pre!=NULL){//判定最后一个节点是不是只出现了一次
pre->next=cur;
}
else if(count>1&&pre!=NULL){
pre->next=NULL;
}
return head;
}


AC结果如下:

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