remove-duplicates-from-sorted-list I&II——去除链表中重复项
2024-08-30 00:41:30
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;
}
};
最新文章
- jQuery带tab切换搜索框样式代码
- jquerymobile仿微信 - 01
- JS之function的应用
- August 12th 2016 Week 33rd Friday
- myeclipse 导入JAVA项目
- Windows,linux快捷键
- NGUI学习笔记(四):动态加载UI和NGUI事件
- android学习日记03--常用控件progressbar/seekbar
- python 零散记录(七)(上) 面向对象 类 类的私有化
- linux调度器系列
- 说一说MVC的Authentication过滤(四)
- Python--logging模块不同级别写入到不同文件
- Cronolog日志分割、定时清理
- ubuntu18.04LTS修改键盘键位
- pythonの信号量
- Fluent动网格【3】:DEFINE_CG_MOTION宏
- Mysql配置参数sync_binlog说明
- uniform_tree以及其变体
- [转载]ASP.NET Error – Adding the specified count to the semaphore would cause it to exceed its maximum count
- com.mysql.jdbc.PacketTooBigException: Packet for query is too large (1169 >; 1024)