题目:

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;
}
};
 

最新文章

  1. 【初探IONIC】不会Native可不可以开发APP?
  2. springmvc学习笔记--mybatis--使用插件自动生成实体和mapper
  3. Yocto开发笔记之《嵌入式linux libcurl编程》(QQ交流群:519230208)
  4. AngularJS 验证
  5. 每天一个Linux命令---tcpdump
  6. ACL权限的学习
  7. 管子&amp;小白
  8. public、protect、private在父类子类中使用
  9. [译] ASP.NET 生命周期 – ASP.NET 上下文对象(五)
  10. 扩展BaseAdapter实现不存储列表项的ListView
  11. HDFS追本溯源:HDFS操作的逻辑流程与源码解析
  12. SpringBoot系列——MyBatis整合
  13. 安装redis报错 you need tcl 8.5 or newer in order to run redis test
  14. poj 2406 Power Srings (kmp循环节) (经典)
  15. google的transformer模型的解释
  16. 微信小程序 - 深度定义骨架屏(提示)
  17. eclipse安装maven时候如果conf文件夹中有setting文件则会以这个文件为主,如果自己设置了user的配置文件则会无效
  18. hdu 4995 离线处理+模拟
  19. 20155236 《Java程序设计》实验三(敏捷开发与XP实践)实验报告
  20. paoding rose controller包及文件名命名规则

热门文章

  1. vue之this.$route.params和this.$route.query的区别
  2. php数据几行代码导出到excel(非插件)
  3. Rabbitmq交换机三种模式介绍
  4. laravel--request类获取传值
  5. HTTP协议②缓存
  6. For循环和闭包问题
  7. js 实现继承
  8. PHP实现微信小程序支付完整版,可以借鉴!
  9. 在centos 6.3系统下安装java、tomcat环境的方法与步骤(方法经过验证,可安装成功)
  10. Python之路,Day5 - 常用模块学习 (转载Alex)