题解 | #单链表的排序#

单链表的排序

http://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

  1. 遍历链表拿到所有节点的值,放入list集合
  2. list集合排序
  3. 对原始链表赋值

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    public ListNode sortInList (ListNode head) {
       
        ListNode tem = head;
        //1.取值
        List<Integer> list = new ArrayList();
        while(tem!=null){
            list.add(tem.val);
            tem = tem.next;
        }
        //2.排序
        Collections.sort(list);
        ListNode res = head;
        int index = 0;
        //3.赋值
        while(res!=null){
            res.val = list.get(index);
            index++;
            res = res.next;
        }
        return head;
    }
}
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务