《leetCode》:Remove Duplicates from Sorted List II
来源:互联网 发布:python字符串截取函数 编辑:程序博客网 时间:2024/05/22 19:10
题目
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结果如下:
0 0
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List II
- [leetcode]Remove Duplicates from Sorted List II
- LeetCode-Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- LeetCode - Remove Duplicates from Sorted List II
- LeetCode | Remove Duplicates from Sorted List II
- LeetCode:Remove Duplicates from Sorted List II
- 【leetcode】Remove Duplicates from Sorted List II
- Leetcode: Remove Duplicates from Sorted List II
- leetcode Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- 如何去除Oracle库表结构中的类空格字符
- 占一篇在天津
- 8.面向对象
- java容器详解
- 思维盛宴之设计模式-代理模式Proxy Pattern
- 《leetCode》:Remove Duplicates from Sorted List II
- 拖动旋转
- 可变参数
- hdu acm1005解题思路
- 9.面向对象
- 自定义Linux 内核驱动模块的编译
- Nginx性能优化
- 10.面向对象
- 黑马程序员 JavaSE-08 Collection(集合)