本文主要是介绍《leetCode》:Remove Duplicates from Sorted List II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目
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结果如下:
这篇关于《leetCode》:Remove Duplicates from Sorted List II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!