class Solution {
private static ListNode[] getArray(ListNode head) {
if (head == null) {
return new ListNode[0];
}
int size = 0;
ListNode p = head;
while (p != null) {
++ size;
p = p.next;
}
ListNode[] result = new ListNode[size];
p = head;
size = 0;
while (p != null) {
result[size ++] = p;
p = p.next;
}
return result;
}
private static ListNode getList(ListNode[] array) {
if (array == null || array.length == 0) {
return null;
}
ListNode head = array[0];
ListNode pre = head;
for (int i = 1;i < array.length; ++ i) {
pre.next = array[i];
pre = array[i];
}
pre.next = null;
return head;
}
private static void swap(ListNode[] array, int a, int b) {
if (a == b) {
return;
}
ListNode t = array[a];
array[a] = array[b];
array[b] = t;
}
private static ListNode function(ListNode head, int val) {
ListNode[] array = getArray(head);
int size = array.length;
int l = -1;
int r = size - 1;
int i = 0;
while (i <= r) {
if (array[i].val < val) {
swap(array, ++ l, i ++);
} else if (array[i].val == val) {
++ i;
} else {
swap(array, i, r --);
}
}
return getList(array);
}
private static void print(ListNode head) {
while (head != null) {
System.out.println(head.val);
head = head.next;
}
}
public static void main(String[] args) {
ListNode n1 = new ListNode(9);
ListNode n2 = new ListNode(0);
ListNode n3 = new ListNode(4);
ListNode n4 = new ListNode(5);
ListNode n5 = new ListNode(1);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
ListNode head = function(n1, 3);
print(head);
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
©著作权归作者所有:来自51CTO博客作者天一涯51CTO的原创作品,如需转载,请注明出处,否则将追究法律责任