I、Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.

PS:遍历,而后记录pre,并删除后续重复node

 /**
* 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 *cur=head,*pre=NULL;
while(cur!=NULL){
if(pre==NULL){
pre=cur;
cur=cur->next;
continue;
}
ListNode *next=cur->next;
if(pre->val==cur->val){
pre->next=next;
}else
pre=cur;
cur=next;
}
return head;
}
};

II、

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.

删除所有重复项。

PS:循环比较next->val==cur->val,若next跳动则剔除cur至next之间的节点。否则右移left指针。

 /**
* 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) {
if(head==NULL) return NULL;
ListNode h(-);
ListNode *res=&h;
res->next=head;
ListNode *cur=head,*pre=NULL,*left=res;
while(cur!=NULL){
ListNode* next=cur->next;
while(next!=NULL&&cur->val==next->val){
next=next->next;
}
if(next==cur->next){
left=cur;
}else{
left->next=next;
}
cur=next;
}
return res->next;
}
};

最新文章

  1. jQuery带tab切换搜索框样式代码
  2. jquerymobile仿微信 - 01
  3. JS之function的应用
  4. August 12th 2016 Week 33rd Friday
  5. myeclipse 导入JAVA项目
  6. Windows,linux快捷键
  7. NGUI学习笔记(四):动态加载UI和NGUI事件
  8. android学习日记03--常用控件progressbar/seekbar
  9. python 零散记录(七)(上) 面向对象 类 类的私有化
  10. linux调度器系列
  11. 说一说MVC的Authentication过滤(四)
  12. Python--logging模块不同级别写入到不同文件
  13. Cronolog日志分割、定时清理
  14. ubuntu18.04LTS修改键盘键位
  15. pythonの信号量
  16. Fluent动网格【3】:DEFINE_CG_MOTION宏
  17. Mysql配置参数sync_binlog说明
  18. uniform_tree以及其变体
  19. [转载]ASP.NET Error – Adding the specified count to the semaphore would cause it to exceed its maximum count
  20. com.mysql.jdbc.PacketTooBigException: Packet for query is too large (1169 > 1024)

热门文章

  1. Vue - methods 方法
  2. Rust学习资源和路线
  3. CSA Round 84 Growing Trees
  4. 1.docker学习
  5. Number String(hdu 4055)
  6. Heritrix3.0.0启动介绍
  7. 【Linux】可重入函数和线程安全的区别与联系【转】
  8. python日期时间相关
  9. 小谈c#数据库存取图片的方式
  10. springBoot 类注释和方法注释