(1)把鏈表放入數組裏,在數組上做partition(筆試用)
(2)分成小、中、大三部分,再把各個部分之間串起來(面試用)
package com.inspire.chapter6;
public class Code03_SmallerEqualBigger {
public static class Node {
public int value;
public Node next;
public Node(int v) {
value = v;
}
}
public static Node listPartition1(Node head, int pivot) {
if (head == null) {
return head;
}
Node cur = head;
int i = 0;
while (cur != null) {
i++;
cur = cur.next;
}
Node[] nodeArr = new Node[i];
cur = head;
for (i = 0; i < nodeArr.length; i++) {
nodeArr[i] = cur;
cur = cur.next;
}
arrPartition(nodeArr, pivot);
for (i = 0; i < nodeArr.length - 1; i++) {
nodeArr[i].next = nodeArr[i + 1];
}
nodeArr[i].next = null;
return nodeArr[0];
}
private static void arrPartition(Node[] nodeArr, int pivot) {
int less = 0;
int more = nodeArr.length;
int index = 0;
while (index < more) {
if (nodeArr[index].value == pivot) {
index++;
} else if (nodeArr[index].value < pivot) {
swap(nodeArr, index++, less++);
} else {
swap(nodeArr, index, --more);
}
}
}
private static void swap(Node[] nodeArr, int i, int j) {
Node temp = nodeArr[i];
nodeArr[i] = nodeArr[j];
nodeArr[j] = temp;
}
private static void printLinkedList(Node head) {
System.out.println("Linked list:");
while (head != null) {
System.out.print(head.value + " ");
head = head.next;
}
System.out.println();
}
public static Node listPartition2(Node head, int pivot) {
Node sH = null;
Node sT = null;
Node eH = null;
Node eT = null;
Node mH = null;
Node mT = null;
Node next = null;
while (head != null) {
next = head.next;
head.next = null;
if (head.value < pivot) {
if (sT == null) {
sH = head;
sT = head;
} else {
sT.next = head;
sT = head;
}
} else if (head.value == pivot) {
if (eT == null) {
eH = head;
eT = head;
} else {
eT.next = head;
eT = head;
}
} else {
if (mT == null) {
mH = head;
mT = head;
} else {
mT.next = head;
mT = head;
}
}
head = next;
}
if (sT != null) {
sT.next = eH;
eH = eH == null ? sT : eH;
}
if (eT != null) {
eT.next = mH;
mH = mH == null ? eT : mH;
}
return sT != null ? sH : (eT != null ? eH : mH);
}
public static void main(String[] args) {
Node head1 = new Node(7);
head1.next = new Node(9);
head1.next.next = new Node(1);
head1.next.next.next = new Node(8);
head1.next.next.next.next = new Node(5);
head1.next.next.next.next.next = new Node(2);
head1.next.next.next.next.next.next = new Node(5);
printLinkedList(head1);
head1 = listPartition2(head1, 8);
printLinkedList(head1);
}
}