编写代码,以给定值x为基准将链表分割成两部分,所有小于x的结点排在大于或等于x的结点之前且原顺序不变
思维逻辑图如下:
先将<x的数字排成一个新链表,将>x的数字拍成一个新链表,最后将这两个链表连在一起即可。
bs:<x新链表的头(b start);
be:<x新链表的尾(b end);
as:>x新链表的头(b start);
ae:>x新链表的尾(b end);
将两个新链表连在一起只需让be指向as即可。
代码如下:
public ListNode partition(int x) {
ListNode cur = this.head;
ListNode bs = null;
ListNode be = null;
ListNode as = null;
ListNode ae = null;
while(cur != null) {
if(cur.data < x) {
//判断是不是第一次插入
if(bs == null) {
bs = cur;
be = bs;
}else {
be.next = cur;
be = be.next;//be = cur;
}
}else {
//判断是不是第一次插入
if(as == null) {
as = cur;
ae = cur;
}else {
ae.next = cur;
ae = ae.next;//ae = cur;
}
}
cur = cur.next;
}
if(bs == null){
return as;
}
be.next = as;
if(as != null) {
ae.next = null;
}
return bs;
}