Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 * 
 * 麻烦的地方在于java里的arraylist不像linkedlist remove以后下标是乱的,所以要用一个int[] removed数组标记哪个list已经到头
 */
public class Solution {
    public ListNode mergeKLists(ArrayList<ListNode> lists) {
        if (lists==null ||lists.size()==0) {
            return null;
        }
        //标记已经遍历完的list
        int[] removed = new int[lists.size()];
        ListNode head = null;
        //每个链表的工作指针
        ArrayList<ListNode> listPtr = new ArrayList<ListNode>();
        //当前合并结果指针在哪个链表
        int current = 0;
        //当前合并结果指针
        ListNode currentPtr = null;
        //确定头指针
        for (int i=0;i<lists.size();i++) {
            listPtr.add(lists.get(i));
            if (lists.get(i)==null) {
                removed[i] = 1;
                continue;
            }
            if (head==null) {
                head = lists.get(i);
                current = i;
            } else if (head.val>lists.get(i).val) {
                head = lists.get(i);
                current = i;
            }
        }
        try {
            currentPtr = listPtr.get(current);
        } catch (Exception e) {
            return null;
        }
        //若果全是空 List 返回null
        if (currentPtr == null) {
            return null;
        } else {
            listPtr.set(current, listPtr.get(current).next);
        }

        while (!listPtr.isEmpty()) {
            ListNode min = null;
            int minIndex = 0;
            //找到最小的节点位置
            for (int i=0;i<listPtr.size();i++) {
                if (removed[i]==1) {
                    continue;
                }
                if (listPtr.get(i) == null) {
                    removed[i] = 1;
                    continue;
                } else if (min == null) {
                    min =listPtr.get(i);
                    minIndex = i;
                } else if (min.val > listPtr.get(i).val) {
                    min = listPtr.get(i);
                    minIndex = i;
                }
            }
            //添加到列表结果
            currentPtr.next = min;
            currentPtr = currentPtr.next;
            //min是null时候全部已经到尾端
            if (currentPtr==null) {
                return head;
            } else {
                //将最小节点移动一个
                listPtr.set(minIndex, listPtr.get(minIndex).next);
            }
        }
        return head;
    }
}

 

posted @ 2014-01-06 11:39  23lalala  阅读(126)  评论(0编辑  收藏  举报