给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
示例:
输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5
//思路:分割链表,定义两个指针,从链表开始遍历,将第一个比x小的数用第一个指针存起来,将第一个比x大或者相等的数用第二个指针存起来,然后剩下的数,当遇到比x小的,用第一个指针的next指向,一次往后,遇到比x大或者相等的也这样,最后判断是否有比x小的数,如果有,ze第一个指针的尾指向第二个指针的头,连起来。最后返回第一个指针头,如果没有,则返回第二个指针头。
/**
* 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 sH = null;
ListNode sT = null;
ListNode bH = null;
ListNode bT = null;
ListNode next = null;
while(head!=null){
next = head.next;
head.next = null;
if(head.val<x){
if(sH==null){
sH = head;
sT = head;
}else{
sT.next = head;
sT = head;
}
}else{
if(bH==null){
bH = head;
bT = head;
}else{
bT.next = head;
bT = head;
}
}
head = next;
}
if(sT!=null){
sT.next = bH;
}
return sH==null?bH:sH;
}
}