[算法]單鏈表的選擇排序

題目:

給定一個無序單鏈表的頭節點head,實現單鏈表的選擇排序。spa

要求:額外空間複雜度爲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;
	}
相關文章
相關標籤/搜索