题解 | #单链表的排序#
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
public ListNode sortInList (ListNode head) {
// write code here
//创建集合,将链表所有节点值添加技巧怒
ArrayList<Integer> list = new ArrayList<>();
ListNode getNum = head;
while (getNum != null) {
list.add(getNum.val);
getNum = getNum.next;
}
//集合值进行排序
Collections.sort(list);
int num=list.get(0);
ListNode tmp=new ListNode(num);
ListNode returnList=tmp;
int i=1;
//将排序好的集合值依次加入链表
for(Integer integer:list){
if(i==1){
i++;
continue;
}else{
ListNode tmpNode=new ListNode(integer);
tmp.next=tmpNode;
tmp=tmp.next;
}
}
return returnList;
}
}
查看18道真题和解析