https://oj.leetcode.com/problems/partition-list/
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.
public ListNode partition(ListNode head, int x)
这一题的解题思路很简单,就是根据x值构造两个list,一个list小于x,另一个list大于等于x即可,用一个tmp指针一路往下扫一路构建。然后连在一起就可以了。需要注意的不过是一些边界条件,譬如说x大于或者小于链表上的所有数。
public ListNode partition(ListNode head, int x) {
ListNode smallHead = null, smalltmp = null, largeHead = null, largetmp = null, tmp = head;
while(tmp != null){
if(tmp.val < x){
if(smallHead == null){
smallHead = tmp;
smalltmp = smallHead;
}else{
smalltmp.next = tmp;
smalltmp = smalltmp.next;
}
}else{
if(largeHead == null){
largeHead = tmp;
largetmp = largeHead;
}else{
largetmp.next = tmp;
largetmp =largetmp.next;
}
}
tmp = tmp.next;
if(smalltmp != null)smalltmp.next = null;
if(largetmp != null)largetmp.next = null;
}
if(smalltmp != null)smalltmp.next = largeHead;
return smallHead == null ? largeHead : smallHead;
本文介绍了解决链表中根据给定值x进行分区的算法,将链表分为两部分,一部分包含所有小于x的节点,另一部分包含所有大于等于x的节点。文章详细解释了解题思路和代码实现。
274

被折叠的 条评论
为什么被折叠?



