编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
思路:
假想两个线段一左一右,定义一个指针 cur,循环遍历这个链表,对于比 x 大的数以尾插法的方式放入左边线段,剩下的以尾插法的方式放入右边的线段,需要定义bs be 为左边线段的头和尾,as ae 为右边线段的头和尾,最后只需要把 两个线段连起来,be.next = as.next,结果 返回 bs 即可
需要注意的是:
如果 bs == null 时,返回 as,其他时候返回 bs,最后当 as != null 时将 ae.next 置为 null
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Partition {
public ListNode partition(ListNode pHead, int x) {
// write code here
if (pHead == null){
return null;
}
ListNode bs = null;
ListNode be = null;
ListNode as = null;
ListNode ae = null;
ListNode cur = pHead;
while (cur != null ){
if (cur.val < x){
//第一次插入
if (bs == null){
bs = be = cur;
}else {
be.next = cur;
be = be.next;
}
}else {
//第一次插入
if (as == null){
as = ae = cur;
}else{
ae.next = cur;
ae = ae.next;
}
}
cur = cur.next;
}
//判断bs 等于 null,返回 as
if (bs == null){
ae.next = null;
return as;
}
//如果 bs 不为空需要拼接
be.next = as;
//如果 ae 不为 null ae.next == null
if (ae != null){
ae.next = null;
}
return bs;
}
}