来自左神书中的一道题,在左神核心代码的基础上,添加了链表的构建和打印操作,将这道题完善成了一个小Demo,和各位共勉。
题目:
给定一个无序单链表的头结点head,实现单链表的选择排序。
要求额外空间复杂度O(1)。
思路:
从未排序链表中找到最小节点small的前一节点smallPre,从而在未排序链表中删除最小节点small,并将最小节点small添加到已排序链表中,由此逐渐缩小未排序链表,实现链表的选择排序。
核心算法:
最小节点small的前一节点smallPre:
public static Node getSmallPreNode(Node head){
Node small = head;
Node smallPre = null;
Node pre = head;
Node cur = head.next;
while(cur != null){
if(cur.value < small.value){
small = cur;
smallPre = pre;
}
pre = cur;
cur = cur.next;
}
return smallPre;
}
选择排序链表:
public static Node SelectionSort(Node head){
Node cur = head;
Node small = null;
Node smallPre = null;
Node tail = null;
while(cur != null){
small = cur;
smallPre = getSmallPreNode(cur);
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;
}
原创不易,转载请注明出处哈。
权兴权意
http://blog.youkuaiyun.com/hxqneuq2012/article/details/53190574
完整源代码:
public class SelectionSortTest {
/**
* 权兴权意-2016.11.10
* 单链表的选择排序
*/
public static void main(String[] args) {
//构建链表5-0
Node head1 = new Node(5);
Node temp1 = head1;
for(int i = 4;i > 0;i--){
temp1.next = new Node(i);
temp1 = temp1.next;
}
printList(head1);
head1 = SelectionSort(head1);
printList(head1);
}
public static Node SelectionSort(Node head){
Node cur = head;
Node small = null;
Node smallPre = null;
Node tail = null;
while(cur != null){
small = cur;
smallPre = getSmallPreNode(cur);
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 getSmallPreNode(Node head){
Node small = head;
Node smallPre = null;
Node pre = head;
Node cur = head.next;
while(cur != null){
if(cur.value < small.value){
small = cur;
smallPre = pre;
}
pre = cur;
cur = cur.next;
}
return smallPre;
}
//打印链表
public static void printList(Node head){
Node temp = head;
while(temp != null){
if(temp.next == null){
System.out.print(temp.value + " ");
break;
}
System.out.print(temp.value + "->");
temp = temp.next;
}
System.out.println();
}
}