Remove Duplicates from Sorted List I,II
2015-09-09 12:39
253 查看
Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
1->1->2, return
1->2.
Given
1->1->2->3->3, return
1->2->3.
Hide Tags
Linked List
<span style="font-weight: normal;"> ListNode* deleteDuplicates(ListNode* head) { if(head==NULL || head->next==NULL) return head; ListNode* pp=head; ListNode* p=head->next; while(p){ if(p->val != pp->val){ pp = pp->next; p = p->next; }else{ pp->next = p->next; p = p->next; } } return head; }</span>
Question
Solution
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.
Hide Tags
Linked List
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* deleteDuplicates(ListNode* head) { if(head==NULL || head->next==NULL) return head; ListNode* pp=new ListNode(-1); pp->next=head; ListNode* p=head; ListNode* cur=pp; while(p){ bool isDuplicates=false; while(p->next != NULL && p->val == p->next->val){ isDuplicates=true; p=p->next; } if(isDuplicates){ p=p->next; continue;//eg.[1,1] } cur->next=p; cur=cur->next; p=p->next; } cur->next=p; return pp->next; } }; void main(){ ListNode *head = new ListNode(1); ListNode *l1 = new ListNode(1); ListNode *l2 = new ListNode(1); ListNode *l3 = new ListNode(2); ListNode *l4 = new ListNode(3); head->next = l1; l1->next = l2; l2->next = l3; l3->next = l4; l4->next = NULL; Solution s; s.deleteDuplicates(head); }
相关文章推荐
- 1097. Deduplication on a Linked List (25)
- 单例模式之内部静态类
- 【剑指offer】面试题7:用两个栈实现队列
- 1096. Consecutive Factors (20)
- 在CentOS上安装部署MooseFS分布式文件系统
- POJ1222 EXTENDED LIGHTS OUT【高斯消元】
- linux下查看网关的命令
- Android中AndroidManifest.xml uses-sdk警告
- 解决Win10 Windows10关键错误 开始菜单和Cortana无法工作问题
- ipvsadm 安装配置
- 【剑指offer】面试题6:重建二叉树
- Second Level Cache for Entity Framework 6.1
- sql事务和锁
- POJ 1724 ROADS(费用最短路:优先队列+BFS)
- 安装RPM套件rpm-build错误解决:NOKEY、elfutils is needed
- 1095. Cars on Campus (30)
- centos 6.6升级自带mysql版本文档
- 使用Charles对手机app网络包进行分析
- hdu 3709 Balanced Number 2010成都区域赛 数位dp
- 整数中1出现的次数(从1到n整数中1出现的次数)(算法)