Java实现-链表排序

xiaoxiao2021-02-28  87

/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The head of linked list. * @return: You should return the head of the sorted linked list, using constant space complexity. */ public ListNode sortList(ListNode head) { // write your code here if(head==null){ return null; } List<Integer> list=new ArrayList<Integer>(); list.add(head.val); while(head.next!=null){ head=head.next; list.add(head.val); } Collections.sort(list); ListNode h=new ListNode(list.get(0)); ListNode node=h; for(int i=1;i<list.size();i++){ node.next=new ListNode(list.get(i)); node=node.next; } return h; } }

转载请注明原文地址: https://www.6miu.com/read-96352.html

最新回复(0)