[程序员代码面试指南]链表问题-单链表的选择排序(选择排序)

Posted coding-gaga

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[程序员代码面试指南]链表问题-单链表的选择排序(选择排序)相关的知识,希望对你有一定的参考价值。

题意

给定一个无序单链表的头节点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;
    

以上是关于[程序员代码面试指南]链表问题-单链表的选择排序(选择排序)的主要内容,如果未能解决你的问题,请参考以下文章

算法总结之 单链表的选择排序

[程序员代码面试指南]链表问题-按照左右半区的方式重新组合单链表

程序员代码面试指南第二版 12.打印两个升序链表的公共部分

[程序员代码面试指南]链表问题-删除无序链表中重复出现的节点

[程序员代码面试指南]链表问题-复制含有随机指针节点的链表(方法二待做)

C语言如何对链表的数进行排序?