题目描述:
给你一个链表的头节点 head 和一个特定值 x ,请你对链表进行分隔,使得所有 小于 x 的节点都出现在 大于或等于 x 的节点之前。
你应当 保留 两个分区中每个节点的初始相对位置。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
if(head==null){
return head;
}
ListNode first = null; //该节点后面链接的是比x小的节点
ListNode second = null; //该节点后面链接的是比x大的节点
ListNode p = head;
ListNode first_rear=null;
ListNode second_rear=null;
while(p!=null){
if(p.val<x){
if(first==null){
first=p;
first_rear=first;
} else{
//将p节点插入到first链表之后 使用尾插法
first_rear.next=p;
first_rear=p;
}
} else{
if(second==null){
second=p;
second_rear=second;
} else{
//将p节点插入到second链表之后 使用尾插法
second_rear.next=p;
second_rear=p;
}
}
p=p.next;
}
if(first_rear==null){
return second;
}
if(second_rear==null){
return first;
}
second_rear.next=null;
first_rear.next=second;
return first;
}
}