タイトル説明
リンクリストのヘッドポインタListNode * pHeadが現在リストされています。特定の値xを指定し、元のデータ順序を変更せずに、xより小さいすべてのノードを残りのノードの前に配置するコードを記述します。ヘッドを返します。再配置されたリストポインタの。
コード:
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Partition {
public ListNode partition(ListNode pHead, int x) {
ListNode be = null;
ListNode ae = null;
ListNode as = null;
ListNode bs = null;
ListNode cur = pHead;
while(cur != null){
if(cur.val < x){
if(bs == null){
//小于x的部分一个节点还没有的情况下
bs = cur;
be = cur;
}else{
//有了节点
be.next = cur;
be = be.next;
}
}else{
if(as == null){
//大于x的部分一个节点还没有的情况下
as = cur;
ae = cur;
}else{
//小于x的部分一个节点还没有的情况下
ae.next = cur;
ae = ae.next;
}
}
cur = cur.next;
}
if(bs == null){
//如果bs为空,返回的是as
return as;
}
be.next = as;
if(as != null){
//as不为空时,我们要把as的最后一个节点置为空
ae.next = null;
}
return bs;
// write code here
}
}