LeetCode86 Partition List
2024-09-06 14:25:57
题目:
Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.(Medium)
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
分析:
把链表归并,其思路就是先开两个链表,把小于x的值接在链表left后面,大于x的值接在链表right后面;
然后把链表left的尾部与链表right的头部接在一起。
注意:链表right的尾部next赋值为nullptr。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode dummy1();
ListNode dummy2();
ListNode* left = &dummy1;
ListNode* right = &dummy2;
while (head != nullptr) {
if (head -> val < x) {
left -> next = head;
left = left -> next;
}
else {
right -> next = head;
right = right -> next;
}
head = head -> next;
}
left -> next = dummy2.next;
right -> next = nullptr;
return dummy1.next;
}
};
最新文章
- 【初探IONIC】不会Native可不可以开发APP?
- springmvc学习笔记--mybatis--使用插件自动生成实体和mapper
- Yocto开发笔记之《嵌入式linux libcurl编程》(QQ交流群:519230208)
- AngularJS 验证
- 每天一个Linux命令---tcpdump
- ACL权限的学习
- 管子&;小白
- public、protect、private在父类子类中使用
- [译] ASP.NET 生命周期 – ASP.NET 上下文对象(五)
- 扩展BaseAdapter实现不存储列表项的ListView
- HDFS追本溯源:HDFS操作的逻辑流程与源码解析
- SpringBoot系列——MyBatis整合
- 安装redis报错 you need tcl 8.5 or newer in order to run redis test
- poj 2406 Power Srings (kmp循环节) (经典)
- google的transformer模型的解释
- 微信小程序 - 深度定义骨架屏(提示)
- eclipse安装maven时候如果conf文件夹中有setting文件则会以这个文件为主,如果自己设置了user的配置文件则会无效
- hdu 4995 离线处理+模拟
- 20155236 《Java程序设计》实验三(敏捷开发与XP实践)实验报告
- paoding rose controller包及文件名命名规则
热门文章
- vue之this.$route.params和this.$route.query的区别
- php数据几行代码导出到excel(非插件)
- Rabbitmq交换机三种模式介绍
- laravel--request类获取传值
- HTTP协议②缓存
- For循环和闭包问题
- js 实现继承
- PHP实现微信小程序支付完整版,可以借鉴!
- 在centos 6.3系统下安装java、tomcat环境的方法与步骤(方法经过验证,可安装成功)
- Python之路,Day5 - 常用模块学习 (转载Alex)