[算法]单链表的选择排序

题目:

给定一个无序单链表的头节点head,实现单链表的选择排序。

要求:额外空间复杂度为O(1)。

程序:

public static Node selectionSort(Node head){
		Node samll=null;//最小的节点		 
		Node tail=null;//排序部分尾部
		Node cur=head;//未排序部分头部
		Node smallPre=null;//最小的节点的前一个节点
		while(cur!=null){
			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 getSmallestPreNode(Node head){
		Node smallPre=null;
		Node small=head;
		Node pre=head;
		Node cur=head.next;
		while(cur!=null){
			if (cur.value<small.value) {
				smallPre=pre;
				small=cur;
			}
			pre=cur;
			cur=cur.next;
		}
		return smallPre;
	}
posted @ 2016-03-08 21:50  小魔仙  阅读(490)  评论(0编辑  收藏  举报