86. 分隔链表
Given the head of a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
Example 1:

Input: head = [1,4,3,2,5,2], x = 3 Output: [1,2,2,4,3,5]
Example 2:
Input: head = [2,1], x = 2 Output: [1,2]
Constraints:
- The number of nodes in the list is in the range
[0, 200]. -100 <= Node.val <= 100-200 <= x <= 200
分隔链表。
给你一个链表和一个特定值 x ,请你对链表进行分隔,使得所有小于 x 的节点都出现在大于或等于 x 的节点之前。
你应当保留两个分区中每个节点的初始相对位置。
思路:申请小于和大于的头尾节点,让其按要求增长成小于和大于等于的链表,最后小于的尾(如果有的话)去联接大于等于的头
在比较时让当前节点独立出来
ListNode cur=head; cur.next=null;
class Solution {
public ListNode partition(ListNode head, int x) {
if(head==null||head.next==null){
return head;
}
ListNode sH=null;
ListNode sT=null;
ListNode bH=null;
ListNode bT=null;
while(head!=null){
ListNode next=head.next;
ListNode cur=head;
//和head链表断联
cur.next=null;
if(cur.val<x){
if(sH==null){
sH=cur;
sT=cur;
}else{
sT.next=cur;
sT=cur;
}
}else{
if(bH==null){
bH=cur;
bT=cur;
}else{
//注意这里指针的变换
bT.next=cur;
bT=cur;
}
}
head=next;
}
if(sT==null){
return bH;
}else{
sT.next=bH;
return sH;
}
}
}
第二种解法,利用辅助节点,让小于和大于等于的处于相同的处理
class Solution {
public ListNode partition(ListNode head, int x) {
// corner case
if (head == null || head.next == null) {
return head;
}
// normal case
ListNode p = new ListNode(0);
ListNode pHead = p;
ListNode q = new ListNode(0);
ListNode qHead = q;
while (head != null) {
// < x成一组
if (head.val < x) {
p.next = head;
p = p.next;
}
// >= x成一组
else {
q.next = head;
q = q.next;
}
head = head.next;
}
p.next = qHead.next;
q.next = null;
return pHead.next;
}
}

浙公网安备 33010602011771号