题目描述
编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前
给定一个链表的头指针 ListNode* pHead,请返回重新排列后的链表的头指针。注意:分割以后保持原来的数据顺序不变。
分析见下图:
要注意这种情况:
大致思路就是这样,还有一些需要注意的情况,当链表为空或链表只有一个结点时,都没办法分割,直接返回null就行。还要注意到bs或as第一次插入结点时和后面再插入时的操作也不一样,具体见下面的代码:
public ListNode partition(ListNode pHead, int x) {
if(pHead == null || pHead.next == null) {
return pHead;
}
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 = cur;
be = cur;
}else {
be.next = cur;
be = be.next;
}
}else {
//是不是第一次插入
if (as == null) {
as = cur;
ae = cur;
}else {
ae.next = cur;
ae = ae.next;
}
}
cur = cur.next;
}
//如果as不为空,那么就让ae.next = null,以防出现死循环的情况
if(as != null) {
ae.next = null;
}
if(bs == null) {
return as;
}
be.next = as;
return bs;
}