给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
Given the head of a linked list, return the list after sorting it in ascending order.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
示例 3:输入:head = []
输出:[]
提示:
链表中节点的数目在范围 [0, 5 * 104] 内
-105 <= Node.val <= 105来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
package Sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortList {
public static ListNode sortList(ListNode head){
if(head == null){
return null;
}
List<ListNode> list = new ArrayList<>();
while (head != null){
list.add(head);
head = head.next;
}
//对list升序
Collections.sort(list, Comparator.comparingInt(n -> n.val));
//将排序后的元素重新加入
for(int i = 1;i < list.size();i++){
list.get(i - 1).next = list.get(i);
}
list.get(list.size() - 1).next = null;
return list.get(0);
}
public static void main(String[] args) {
ListNode head = new ListNode(2, new ListNode(3, new ListNode(1)));
ListNode node = sortList(head);
while (node != null){
System.out.println(node.val);
node = node.next;
}
}
}
class ListNode {
public ListNode next;
public int val;
//private int val;
//private ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}