题解 | #单链表的排序#

单链表的排序

http://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
        if(head == null){
            return null;
        }
        //查找链表长度
        ListNode cur = head;
        int length = 0;
        while(cur != null){
            length++;
            cur = cur.next;
        }
        //将链表的值放入到数组中并进行排序
        int[] arr = new int[length];
        ListNode cur1 = head;
        for(int i = 0; i < arr.length; i++){
            arr[i] = cur1.val;
            cur1 = cur1.next;
        }
        Arrays.sort(arr);
        //将数组的值再放入到聊表中
        ListNode cur2 = head;
        for(int i = 0; i<arr.length; i++){
            cur2.val = arr[i];
            cur2 = cur2.next;
        }
        return head;
    } 
}
全部评论

相关推荐

头像
06-12 10:39
Java
给你们全都来一刀:你了解回暖的核心逻辑吗,读过回暖的源码吗,上线过回暖相关的项目吗
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务