題目:
編寫程序以 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 min=new ListNode(0);
ListNode minhead=min;
ListNode max=new ListNode(0);
ListNode maxhead=max;
while(head!=null){
if(head.val<x){
min.next=head;
head=head.next;
min=min.next;
}else{
max.next=head;
head=head.next;
max=max.next;
}
}
min.next=maxhead.next;
max.next=null;
return minhead.next;
}
}