分析:
题目要求将链表以x为基准分成两部分,但并不是真的将链表分成两个链表,同时在分割后,不能改变原先链表的顺序,具体分析步骤如下:
- 首先我们定义一个cur去遍历链表的每一个节点,找出所有小于x的结点排在大于或等于x的结点之前
- 这里我们就有两部分数据,一部分是小于x,另一部分是大于等于x,所以我们需要先重新定义两个链表,头和尾分别是bs,be和as,ae,将小于x的数据放在bs链表里,将大于等于x的数据放在as链表里
- 对于链表我们有头插,尾插和中间插入三种方法,但这里题目要求在分割后不能改变原先链表的顺序,所以我们选择尾插法
- 当遍历完链表将数据分别放在bs和as链表下后,我们要将两个链表连接在一起
- 最后返回头节点,在返回是要判断bs是否为空,如果为空,则返回as
代码示例:
//尾插法
public void addLast(int data) {
ListNode node = new ListNode(data);
ListNode cur = this.head;
if(this.head == null) {
this.head = node;
}else {
while(cur.next != null) {
cur = cur.next;
}
cur.next = node;
}
}
//以给定值x为基准将链表分割成两部分
public ListNode partition(int x) {
ListNode bs = null;
ListNode be = null;
ListNode as = null;
ListNode ae = null;
ListNode cur = this.head;
while(cur != null) {
if(cur.data < 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;
}
结果展示: