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:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
模拟题。
1.用链1记录所有<x的nodes。
2.用链2记录所有>=x的nodes。
3.合并链1链2.
细节:
1.需要dummy1, dummy2, p1, p2。dummy.next指着链的头。p1 p2指着当前链延伸情况下的最后一个node。
实现:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode partition(ListNode head, int x) { // 1. find nodes < x, dummynode1 // 2. find nodes >= x, dummynode2 // 3. connect two links ListNode dummy1 = new ListNode(-1); ListNode dummy2 = new ListNode(-1); ListNode p1 = dummy1, p2 = dummy2; while (head != null) { if (head.val < x) { p1.next = head; p1 = p1.next; } else { p2.next = head; p2 = p2.next; } head = head.next; } p1.next = dummy2.next; p2.next = null; return dummy1.next; } }