题解 | #单链表的选择排序#

import java.io.;
import java.util.
;

class Node{
public int value;
public Node next;
public Node(int data){
this.value=data;
}

//String数组转链表   非环
public  static Node tranStringNoLoop(String[] nums){
    Node head=new Node(Integer.parseInt(nums[0]));
    Node cur=head;
    for(int i=1;i<nums.length;i++){
        cur.next=new Node(Integer.parseInt(nums[i]));
        cur=cur.next;
    }
    return head;
}

//int数组转链表  非环
public  static Node tranIntegerNoLoop(int[] nums){
    Node head=new Node(nums[0]);
    Node cur=head;
    for(int i=1;i<nums.length;i++){
        cur.next=new Node(nums[i]);
        cur=cur.next;
    }
    return head;
}

//打印链表[非环]
public static  void printNodeList(Node head){
    StringBuilder sb=new StringBuilder();
    while (head!=null){
        sb.append(head.value).append(" ");
        head=head.next;
    }
    System.out.println(sb.toString());
}

}

public class Main{
public static Node selectionSort(Node head){
Node tail=null; //排序部分尾部
Node cur=head; //未排序部分头部
Node smallPre=null; //最小节点的前一个节点
Node small=null; //最小的节点

    while(cur!=null){
        small=cur;
        smallPre=getSmallestPreNode(cur);
        if(smallPre!=null){
            //删除最小的节点
            small=smallPre.next;
            smallPre.next=small.next;
        }
        //如果最小节点为当前节点,改变头;否则不变
        cur= cur==small?cur.next:cur;
        //将small连接到排序部分尾部
        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;

}

public static void main(String[]args)throws IOException{
    BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
    in.readLine();
    String[] nums=in.readLine().split(" ");
    Node head=Node.tranStringNoLoop(nums);
    head=selectionSort(head);
    Node.printNodeList(head);
}

}

全部评论

相关推荐

家人们,我现在真的好纠结。我是26届的,目前还没有实习过。我现在的情况是,想参加秋招,但是感觉自己的简历特别空,没有实习经历会不会秋招直接凉凉啊?可我又听说现在很多公司对26届实习生也不太感冒,说什么不确定性大。而且我最近在准备考公,时间上也有点冲突。要是把时间花在实习上,备考时间就少了。但要是不实习,又怕以后就业有问题😫有没有懂行的友友帮我分析分析:26届现在不实习,秋招找工作真的会很难吗?考公和实习该怎么平衡啊?如果现在不实习,考完公再去找实习还来得及吗?真的太焦虑了,希望大家能给我点建议🙏
小破站_程序员YT:我可能和大家的观点不一样。人的精力是有限的,不能既要还要。你又想实习又想考公最后又要秋招上岸,我觉得哪有那么多的选择。你如果想考上岸,那就全力以赴。如果想秋招上岸,就继续投实习,投没了,就继续准备秋招,秋招不行继续春招。别到最后,考公没上岸,觉得是花了时间浪费在找实习上了, 秋招没上岸,觉得是浪费时间准备考公去了。我是认为很难说可以去平衡 不喜勿喷,可以叫我删除
实习与准备秋招该如何平衡
点赞 评论 收藏
分享
06-02 15:17
门头沟学院 Java
心爱的idea:怎么会呢 应该是打招呼有问题 问就说实习6个月全国可飞随时到岗
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务