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
.
這道題沒看答案之前不明白到底如何移動氮唯,看了答案發(fā)現(xiàn)太簡單了饼齿。new兩個鏈表,遍歷原鏈表,把val大于等于x的節(jié)點(diǎn)接到big后面留瞳,把val小于x的節(jié)點(diǎn)接到small后面组砚,最后把big接到small后面,就可以了薄霜。
/**
* 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) {
if (head == null || head.next == null){
return head;
}
ListNode big = new ListNode(-1);
ListNode small = new ListNode(-1);
ListNode bighead = big;
ListNode smallhead = small;
while (head != null){
if (head.val < x){
smallhead.next = head;
smallhead = smallhead.next;
} else {
bighead.next = head;
bighead = bighead.next;
}
head = head.next;
}
bighead.next = null;
smallhead.next = big.next;
return small.next;
}
}