- 链表分割:现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。
基本思想:
1.新建两个链表,一个放小于x值的结点,一个放大于x的结点
2.用a1,a2,b1,b2分别标记这两个链表的头和尾
3.用cur遍历原链表,以头插法把各个结点放到相对应的新链表中
4.分析新的两个链表是否有空的情况,若不为空,则把第一个链表的尾拼接到第二个链表的头
5.最后一个结点的next置空
public class Partition {
public ListNode partition(ListNode pHead, int x) {
ListNode a1 = null;
ListNode a2 = null;
ListNode b1 = null;
ListNode b2 = null;
ListNode cur = pHead;
while(cur != null){
if(cur.val < x){
if(a1 == null){
a1 = cur;
a2 = cur;
}
else{
a2.next = cur;
a2 = cur;
}
}
else{
if(b1 == null){
b1 = cur;
b2 = cur;
}
else {
b2.next = cur;
b2 = cur;
}
}
cur = cur.next;
}
if(a1 == null){
if(b1 == null){
return null;
}
b2.next = null;
return b1;
}
else{
if(b1 == null){
a2.next = null;
}
else{
a2.next = b1;
b2.next = null;
}
return a1;
}
}
}