題目:
思路1:
把單向鏈表轉(zhuǎn)化為結(jié)點(diǎn)數(shù)組陈症,利用數(shù)組的partition過(guò)程(快排中),劃分成要求的大于區(qū)小于區(qū)等于區(qū)
注意:在數(shù)組中震糖,以上for循環(huán)沒(méi)有規(guī)定最后一個(gè)節(jié)點(diǎn)指針指向哪录肯,默認(rèn)不是指向null,是個(gè)野指針吧吊说,另外论咏,這里的i在上一步的for循環(huán)已經(jīng)變成7了
代碼1:
public static class Node {
public int value;
public Node next;
public Node(int data) {
this.value = data;
}
}
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];
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 static void arrPartition(Node[] 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 static void swap(Node[] nodeArr, int a, int b) {
Node tmp = nodeArr[a];
nodeArr[a] = nodeArr[b];
nodeArr[b] = tmp;
}
思路2:
創(chuàng)建三個(gè)單鏈表优炬,代表小于鏈表,大于鏈表厅贪,等于鏈表蠢护,通過(guò)比較整出鏈表,然后將三個(gè)鏈表合并起來(lái)
注意卦溢,代碼中有一步是糊余,next = head.next秀又, head.next=null单寂,這一步是必須的,因?yàn)槟阍诮o每個(gè)區(qū)域的尾部賦值的時(shí)候吐辙,使用比如sT=head宣决,如果head.next!=null的話昏苏,sT后面就拼接整個(gè)原來(lái)的單鏈表尊沸。此外在拼接的時(shí)候注意條件,具體看注釋贤惯。
代碼2:
public static Node listPartition2(Node head, int pivot) {
Node sH = null; // small head
Node sT = null; // small tail
Node eH = null; // equal head
Node eT = null; // equal tail
Node bH = null; // big head
Node bT = null; // big tail
Node next = null; // save next node
// every node distributed to three lists
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;
}
// small and equal reconnect
if (sT != null) {
sT.next = eH;
//如果等于區(qū)是空洼专,說(shuō)明上一行的sT.next = =null了,然后eT==null就把sT給eT孵构,eT就相當(dāng)于原來(lái)的sT了
eT = eT == null ? sT : eT;
}
// all reconnect
if (eT != null) {
eT.next = bH;
}
return sH != null ? sH : eH != null ? eH : bH;
}