ParttiTion List 划分链表

来源:互联网 发布:mac flash发热 编辑:程序博客网 时间:2024/05/21 17:17

ParttiTion 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.

这道题要求我们划分链表,把所有小于给定值的节点都移到前面,大于该值的节点顺序不变,相当于一个局部排序的问题。

package leetcode;

/*
* 要求把小于x的元素按顺序放到链表前面。我们仍然是使用链表最常用的双指针大法,一个指向当前小于x的最后一个元素,
* 一个进行往前扫描。如果元素大于x,那么继续前进,否则,要把元素移到前面,并更新第一个指针。
* */

public class PartionList {
public ListNode partion (ListNode head ,int x){
if(head==null){
return null;
}
ListNode helper=new ListNode(0);
helper.next=head; //使用helper便于直接返回修改后的链表;
ListNode walker=helper;
ListNode runner=helper;
while(runner.next!=null){
if(runner.next.val