【题目】给定一个无序单链表的头节点head,实现单链表的选择排序。
要求:额外空间复杂度为O(1)。
public class SelectSortNode {
public static class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
public static Node selectSort(Node head) {
Node smallPre = null;// 最小节点的前一节点
Node small = null;// 最小节点
Node tail = null;// 排序链表部分尾部
Node cur = head;// 未排序部分头部
while (cur != null) {
small = cur;
smallPre = getSmallestPre(head);
if (smallPre != null) {
small = smallPre.next;
smallPre.next = small.next;
}
cur = cur == small ? cur.next : cur;
if (tail == null) {
head = small;
} else {
tail.next = small;
}
tail = small;
}
return head;
}
public static Node getSmallestPre(Node head) {
Node small = head;
Node smallPre = null;
Node pre = head;
Node cur = head.next;
while (cur != null) {
if (small.value > cur.value) {
small = cur;
smallPre = pre;
}
pre = cur;
cur = cur.next;
}
return smallPre;
}
}