题解 | #合并k个已排序的链表#

合并k个已排序的链表

http://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

我这操作有点骚啊,不知道真正面试的时候会不会被喷

先遍历放到List里面存起来节点的值,然后再新建个链表返回

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

import java.util.*;

public class Solution {
    public ListNode mergeKLists(ArrayList<ListNode> lists) {

        if(lists==null || lists.size()==0){
            return null;
        }

        ArrayList<Integer> numList = new ArrayList<>();
        for(ListNode listNode : lists){
            while(listNode!=null){
                numList.add(listNode.val);
                listNode = listNode.next;
            }
        }
        Collections.sort(numList);
        ListNode buildNode = new ListNode(-1);
        ListNode resNode = buildNode;
        for(Integer item : numList){
            ListNode node = new ListNode(item);
            buildNode.next = node;
            buildNode = buildNode.next;
        }

        return resNode.next;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务