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.
一刷
題解:
創(chuàng)建兩個新鏈表办绝,每次當(dāng)前節(jié)點值比x小的放入headA鹃觉,其余放入headB,最后把兩個鏈表接起來浅侨。 要注意把右側(cè)鏈表的下一節(jié)點設(shè)置為null机隙。
Time Complexity - O(n)蜘拉, Space Complexity - O(1)
/**
* 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 headLeft = new ListNode(-1);
ListNode headRight = new ListNode(-1);
ListNode nodeLeft = headLeft;
ListNode nodeRight = headRight;
while(head != null){
if(head.val < x){
nodeLeft.next = head;
nodeLeft = nodeLeft.next;
} else {
nodeRight.next = head;
nodeRight = nodeRight.next;
}
head = head.next;
}
nodeRight.next = null;
nodeLeft.next = headRight.next;
return headLeft.next;
}
}