实现链表题目: 给定 x, 把一个链表整理成前半部分小于 x, 后半部分大于等于 x 的形式
class Node {
public int val;
public Node next;//类型是Node null
public Node(int val) {
this.val = val;
}
}
//以x为基准进行分割代码
public Node partition(Node pHead, int x) {
// write code here
if(pHead == null) {
return null;
}
Node cur = pHead;
Node as = null;//>x
Node ae = null;
Node bs = null;//<x
Node be = null;
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;
//检查最后一段是不是有数据,如果有,那么我们需要进行把最后一个节点的next置为空,否则会出现死循环
if(as != null) {
ae.next = null;
}
return bs;
}
public static void main(String[] args) {
SingleLinkedList sl = new SingleLinkedList();
sl.addLast(8);
sl.addLast(3);
sl.addLast(5);
sl.addLast(6);
sl.addLast(2);
sl.myToString();
System.out.println();
sl.myToString(sl.partition(sl.head,4));