Remove Duplicates from Sorted List II
来源:互联网 发布:淘宝千牛快捷短语大全 编辑:程序博客网 时间:2024/05/29 02:56
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
.
1 需要一个dummy header来让头处理变得简单
2 维护两个指针,一个为当前指针,一个为重复指针:如果重复指针不为当前指针的后一个,那么删掉从当前往后包括重复指针的所有元素。否则向前挪动当前指针。。。
3. 注意的是无论上一题还是这一题在处理重复指针的时候都是用的p->next=p2->next。 这个地方错了两回了。。。sigh...!!!
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:ListNode *deleteDuplicates(ListNode *head) {ListNode* p=new ListNode(INT_MIN);p->next=head;head=p;while(p->next){ListNode* p2=p->next;while(p2->next && p2->val==p2->next->val)p2=p2->next;if (p->next!=p2){ListNode* tmp=p->next;p->next=p2->next;deleteDup(tmp,p2->next);} else {p=p->next;}}ListNode *new_head=head->next;delete head;return new_head;}void deleteDup(ListNode* beg, ListNode* end){ListNode* cur=beg;while(cur!=end){ListNode* tmp=cur;cur=cur->next;delete tmp;}}};
0 0
- 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
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [leetcode]Remove Duplicates from Sorted List II
- Linux学习之CentOS(十三)--CentOS6.4下Mysql数据库的安装与配置
- zoj 3494 BCD Code (ac自动机+数位dp)
- windows 2012 AD 夺取主机角色
- mysql命令备份和还原
- Android最佳性能实践(二)——分析内存的使用情况
- Remove Duplicates from Sorted List II
- JSoup HTML解析器
- CSS中的EM属性之弹性布局
- Android中的几种网络请求方式详解
- java web 创建阻塞队列demo
- Linux下WebLogic12安装
- 《JAVA与模式》之观察者模式
- Vim复制粘贴与寄存器
- PHP5 mysqli 教程