題目
題目鏈接
編寫程序以 x 爲基準分割鏈表,使得所有小於 x 的節點排在大於或等於 x 的節點之前。如果鏈表中包含 x,x 只需出現在小於 x 的元素之後(如下所示)。分割元素 x 只需處於“右半部分”即可,其不需要被置於左右兩部分之間。
示例:
輸入: head = 3->5->8->5->10->2->1, x = 5
輸出: 3->1->2->10->5->5->8
實現思路
暴力o(n) 篩選出小於x的值,篩選出大於等於x的值,利用頭插法構建單鏈表先將所有小於x的值插入,後將大於等於x的值插入。
代碼實現
/**
* 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) {
//篩選出來小於x的值
List<Integer> min = new ArrayList<>();
//篩選出來大於等於x的值
List<Integer> other = new ArrayList<>();
while (head != null) {
if (head.val < x) {
min.add(head.val);
} else {
other.add(head.val);
}
head = head.next;
}
//利用頭插法構建鏈表 先構建所有小於x的值 在構建所有大於等於x的值
ListNode answer = new ListNode(0);
ListNode temp = answer;
for (int i : min) {
ListNode p = new ListNode(i);
answer.next = p;
answer = p;
}
for (int i : other) {
ListNode p = new ListNode(i);
answer.next = p;
answer = p;
}
return temp.next;
}
}