Java实现-链表排序

来源:互联网 发布:linux配置监控 编辑:程序博客网 时间:2024/06/01 21:24


/** * 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;    }}