82-Remove Duplicates from sorted list II
来源:互联网 发布:2017年it行业前景知乎 编辑:程序博客网 时间:2024/05/19 23:10
难度:medium
类别:linked list
1.题目描述
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.
2.算法分析
遍历一遍链表,并且对相同值的节点进行计数,同时维护一个变量用于记录前面节点的值,如果当前节点的值与前面节点的值pre相同的话,count+1,直到当前节点的值与前面节点的值不同的时候,判断count的值是否大于1,如果刚好等于1的话,就将前面pre值的节点加入到新的链表中。
最后判断count的值是否为1,因为每次加入新的链表的节点是前面的节点,所以最后计数的节点值还需要判断并加入到新的链表中。
需要注意的时候,对于最后进行判断的值,有可能新的链表还没有建立(比如:1 1 2),所以需要进行特殊处理。
3.代码实现
// 给定已经排序的链表,将重复的节点删除,包括本身ListNode* deleteDuplicates(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode* temp = NULL; ListNode* result = NULL; int headVal = head->val; int pre = head->val; int count = 0; while (head != NULL) { if (head->val == pre) { count++; head = head->next; continue; } if (count == 1) { if (temp == NULL) { temp = new ListNode(pre); result = temp; } else { temp->next = new ListNode(pre); temp = temp->next; } } else { count = 1; } pre = head->val; head = head->next; } // 注意当1 1 2的时候,因为前面的1 1已经删掉了,所以只剩下最后一个节点2,但是此时新的 // 链表还没有建立 if (count == 1) { if (temp == NULL) { temp = new ListNode(pre); result = temp; } else { temp->next = new ListNode(pre); } } return result;}
注:用于测试的main函数可以参见前面几篇博客。本题难度其实不大。
阅读全文
0 0
- 82Remove Duplicates from Sorted List II
- 82 Remove Duplicates from Sorted List II
- 82-Remove Duplicates from sorted list II
- LeetCode: Remove Duplicates from Sorted List II
- 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
- Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove duplicates from sorted list II
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- 防止DNS污染,顺利下载caffe依赖文件
- CCF认证 201509-1:数列分段
- 调了一天的配置VS2012+opencv2.4.10
- Ubuntu下为python下载python-tk软件包
- intToRoman算法题
- 82-Remove Duplicates from sorted list II
- Python中的闭包-closure
- Ionic3项目实战
- sdnu1075.我们爱汉诺塔
- 10-29C-homework
- 《从零开始写Javaweb框架》知识点--依赖注入的实现
- 转载大神的文章,解读FAST R-CNN(fast r-cnn)
- python--readline()
- 20171102_四驱台架工作日志