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
.
将一个链表划以x为界限划分为两部分,左边小于x,右边的大于等于x,两边的顺序相对不变。
解法比较简单,没有什么特殊的技巧,分别记录左边和右边的节点即可。
主要是注意最后要让右边的结尾 List2.next = null,否则可能会成环。
比如[2,1],k=2时,如果不加 List2.next = null ,就会成环。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode partition(ListNode head, int x) { if( head == null || head.next == null) return head; ListNode List1 = new ListNode(0); ListNode List2 = new ListNode(0); ListNode result = List1; ListNode ll = List2; ListNode flag = head; while( flag != null){ if( flag.val < x){ List1.next = flag; List1 = List1.next; }else{ List2.next = flag; List2 = List2.next; } flag = flag.next; } List2.next = null; List1.next = ll.next; return result.next; } }