編寫程序以 x 爲基準分割鏈表,使得所有小於 x 的節點排在大於或等於 x 的節點之前。如果鏈表中包含 x,x 只需出現在小於 x 的元素之後(如下所示)。分割元素 x 只需處於“右半部分”即可,其不需要被置於左右兩部分之間。
示例:
輸入: head = 3->5->8->5->10->2->1, x = 5
輸出: 3->1->2->10->5->5->8
題解:
/**
* 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) {
//雙指針法
ListNode cur = head;
ListNode pre = head;
while(cur!=null){
if(cur.val<x){
int tmp = cur.val;
cur.val = pre.val;
pre.val = tmp;
pre = pre.next;
}
cur = cur.next;
}
return head;
}
}