package com.my.util;
public class SingleNode {
public int value;
public SingleNode next;
public SingleNode(int data){
this.value = data;
}
}
package com.my.suanfa;
import com.my.util.SingleNode;
public class Solution05 {
public SingleNode listPatition1(SingleNode head, int pivot) {
if(head == null) {
return head;
}
SingleNode cur = head;
int i = 0;
while(cur != null) {
i++;
cur = cur.next;
}
SingleNode[] nodeArr = new SingleNode[i];
i = 0;
cur = head;
for(i = 0; i < nodeArr.length; i++) {
nodeArr[i] = cur;
cur = cur.next;
}
arrPartition(nodeArr, pivot);
for(i = 1; i < nodeArr.length; i++) {
nodeArr[i - 1].next = nodeArr[i];
}
nodeArr[i - 1].next = null;
return nodeArr[0];
}
public void arrPartition(SingleNode[] nodeArr, int pivot) {
int small = -1;
int big = nodeArr.length;
int index = 0;
while(index != big) {
if(nodeArr[index].value < pivot) {
swap(nodeArr, ++small, index++);
} else if(nodeArr[index].value == pivot) {
index++;
}else {
swap(nodeArr, --big, index);
}
}
}
public void swap(SingleNode[] nodeArr, int a, int b) {
SingleNode tmp = nodeArr[a];
nodeArr[a] = nodeArr[b];
nodeArr[b] = tmp;
}
public SingleNode listPartition2(SingleNode head, int pivot) {
SingleNode sH = null;
SingleNode sT = null;
SingleNode eH = null;
SingleNode eT = null;
SingleNode bH = null;
SingleNode bT = null;
SingleNode next = null;
while(head != null) {
next = head.next;
head.next = null;
if(head.value < pivot) {
if(sH == null) {
sH = head;
sT = head;
} else {
sT.next = head;
sT = head;
}
} else if(head.value == pivot) {
if(eH == null) {
eH = head;
eT = head;
}else {
eT.next = head;
eT = head;
}
} else {
if(bH == null) {
bH = head;
bT = head;
} else {
bT.next = head;
bT = head;
}
}
head = next;
}
if(sT != null) {
sT.next = eH;
eT = eT == null ? sT : eT;
}
if(eT != null) {
eT.next = bH;
}
return sH != null ? sH : eH != null ? eH : bH;
}
}