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.
Example
Given 1->4->3->2->5->2->null and x = 3, return 1->2->2->4->3->5->null.
注意:
分开两个大小链表来连接大小的节点,节点连接到大小链表之后,不需要将其的next 更新为 null,到最后设置 big 最后一个的 next 为 null 即可。
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @param x: an integer
* @return: a ListNode
*/
public ListNode partition(ListNode head, int x) {
// write your code here
ListNode dummy1 = new ListNode(0);
ListNode smallLast = dummy1;
ListNode dummy2 = new ListNode(0);
ListNode bigLast = dummy2;
while (head != null) {
if (head.val < x) {
smallLast.next = head;
smallLast = smallLast.next;
} else {
bigLast.next = head;
bigLast = bigLast.next;
}
head = head.next;
}
smallLast.next = dummy2.next;
bigLast.next = null;
return dummy1.next;
}
}