Partition List
2016-05-04 22:12
134 查看
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.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
/** * 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) { if(!head){ return head; } ListNode leftDummy(0); leftDummy.next = NULL; ListNode rightDummy(0); rightDummy.next = NULL; ListNode * curLeft = &leftDummy; ListNode * curRight = &rightDummy; ListNode * cur = head; while(cur){ if(cur->val < x){ curLeft->next = cur; curLeft = curLeft->next; }else{ curRight->next = cur; curRight = curRight->next; } cur = cur->next; } curLeft->next = NULL; curRight->next = NULL; if(!leftDummy.next){ return rightDummy.next; }else{ curLeft->next = rightDummy.next; return leftDummy.next; } } };
相关文章推荐
- 自由落体
- RS WLAN产品测试全面解决方案
- [打字练习]Four
- 利用谷歌 kaptcha 进行验证码生成
- C++两个栈实现一个队列和两个队列实现一个栈
- CentOS6.5环境使用keepalived实现nginx服务的高可用性及配置详解
- poll设备方法
- POJ 1741 Tree
- mysql为已经建立的表设置其主键(primary key)
- java并发编程(14)--java的守护线程与非守护线程
- 【SSH网上商城项目实战01】整合Struts2、Hibernate4.3和Spring4.2
- CentOS6.5环境使用keepalived实现nginx服务的高可用性及配置详解
- 腾讯面试相关资料
- 1年日记(5月篇)
- Leetcode 147. Insertion Sort List
- 242. Valid Anagram
- 【BZOJ4534】基础排序算法练习题
- 学习Unity射线的创建使用
- windows磁盘分区
- /基本命令/shell提示符