CM11 链表分割
较难
描述
现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。
思路
(1)先令cur=head,把链表分成两段,第一段为小于目标值得,第二段为大于等于目标值的
(2)让cur遍历链表并判断节点放入哪一段里,直到cur==null;
(3)若cur.val<x,把cur尾插法到第一段里(分为是否第一次,如是第一次放进去就行了),若cur.val>=x,一样的方法
(4)循环结束后把第二段尾插到第一段最后就行了,返回bs
(5)最后要判断所有节点都在某一段的情况,若都在第二段,头结点就应是as
(6)在判断若第二段有节点,则要把第二段ae.next设为null,防止链表成环
/**
*现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,
* 且不能改变原来的数据顺序,返回重新排列后的链表的头指针。
* @param x
* @return
*/
public ListNode partition(int x) {
// write code here
ListNode bs = null;//before start
ListNode be = null;//before end
ListNode as = null;//after start
ListNode ae = null;//after end
ListNode cur = head;
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;
}
//预防第一段为空
if (bs == null){
return as;
}
be.next = as;
//预防第二段当中的数据,最后一个结点不是空的
if (as != null){
ae.next = null;
}
return bs;
}