zoukankan      html  css  js  c++  java
  • [程序员代码面试指南]链表问题-单链表的选择排序(选择排序)

    题意

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

    题解

    • 按选择排序方法:每次从原链表找出最小值,从原链表删除,插入新的有序链表。
    • 时间复杂度O(n^2) 额外空间复杂度O(1)

    代码

    public class Main {
    	public static void main(String args[]) {
    		Node n1=new Node(2);
    		Node n2=new Node(1);
    		Node n3=new Node(3);
    		n1.next=n2;
    		n2.next=n3;
    		Node head=n1;
    		
    		Node sortHead=selectSort(head);
    		Node pNode=sortHead;
    		while(pNode!=null) {
    			System.out.println(pNode.val);
    			pNode=pNode.next;
    		}
    	}
    	
    	public static Node selectSort(Node head) {
    		Node cur=head;//无序链表头
    		Node small=null;//最小节点
    		Node smallPre=null;
    		Node tail=null;//有序链表结尾
    		while(cur!=null) {
    			//从原链表找small及删small节点
    			smallPre=getSmallPreNode(cur);
    			if(smallPre==null) {
    				small=cur;
    			}
    			else {
    				small=smallPre.next;
    				smallPre.next=small.next;//删除small节点
    			}
    			
    			//更新cur节点
    			cur=cur==small?cur.next:cur;
    			
    			//把small节点插入有序链表
    			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 cur=head.next;
    		Node pre=head;
    		while(cur!=null) {
    			if(cur.val<small.val) {
    				small=cur;
    				smallPre=pre;
    			}
    			pre=pre.next;
    			cur=cur.next;
    		}
    		return smallPre;
    	}
    }
    
  • 相关阅读:
    POJ3094 UVALive3594 HDU2734 ZOJ2812 Quicksum【进制】
    UVALive5583 UVA562 Dividing coins
    POJ1979 HDU1312 Red and Black【DFS】
    POJ1979 HDU1312 Red and Black【DFS】
    POJ2386 Lake Counting【DFS】
    POJ2386 Lake Counting【DFS】
    HDU4394 Digital Square
    HDU4394 Digital Square
    UVA213 UVALive5152 Message Decoding
    UVA213 UVALive5152 Message Decoding
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/10957937.html
Copyright © 2011-2022 走看看