Middle-题目84:82. Remove Duplicates from Sorted List II
来源:互联网 发布:yunos自动删除软件 编辑:程序博客网 时间:2024/05/01 04:01
题目原文:
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.
题目大意:
给出一个排序好的链表,删除所有重复元素,只保留一个,且保持原来的顺序。
题目分析:
维护两个指针p1和p2,其中p2指向p1下一个节点,每次判断p1和p2的值是否相等,如果相等则删掉p2,且p2向后推,直到p2不等于p1,再令p1等于p2继续判断,总共扫描一遍链表即可。
源码:(language:c)
struct ListNode* deleteDuplicates(struct ListNode* head) { if (!head || !head->next) return head; else { struct ListNode* ptr1 = head, *ptr2 = head; while (ptr2) { ptr1 = ptr2; while (ptr2 && ptr2->val == ptr1->val) ptr2 = ptr2->next; if (ptr1->next == ptr2) // no duplicate ptr1 = ptr2; else if (ptr1 == head) head = ptr2; else { struct ListNode* prev = head; while (prev->next != ptr1) prev = prev->next; prev->next = ptr2; ptr1 = ptr2; } } return head; } }
成绩:
4ms,beats 8.00%,众数4ms,92%
0 0
- Middle-题目84:82. Remove Duplicates from Sorted List II
- Middle-题目47:80. Remove Duplicates from Sorted Array II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 82. Remove Duplicates from Sorted List II
- 数据挖掘方法比较
- Java之——使用JMX监控Tomcat
- 一个不怕机器识别的图形验证码方案
- Android自动化测试之Robotium学习(二)
- Logistic回归总结
- Middle-题目84:82. Remove Duplicates from Sorted List II
- 4.自定义View
- 常用负载均衡算法
- 查找笔记
- FragmentActivity和Activity的具体区别在哪里
- VRP系统——6
- Bash shell command 速查手册
- Adapter数据变化改变现有View的实现
- 点击手势增加,造成crash注意事项UITapGestureRecognizer