您的位置:首页 > 其它

104-合并k个排序链表

2017-10-16 11:02 477 查看
2017.10.16.终于有时间继续刷刷题了。

果然一做链表的题逻辑很清楚,就是这个写起来就很乱。

k个链表就是两两的合并就好了。

/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
public ListNode mergeKLists(List<ListNode> lists) {
// write your code here
if(lists.size() == 0){
return null;
}
ListNode res = lists.get(0);
if(lists.size() == 1){
return res;
}
for(int i = 1; i < lists.size() ; i++){
ListNode tmp = lists.get(i);
res = merger(res,tmp);
}
return res;
}
public ListNode merger(ListNode l1,ListNode l2){
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
ListNode flag = new ListNode(-1);//头结点的位置
ListNode res = flag;//插入的位置
while(l1 != null && l2 != null){
if(l1.val < l2.val){
flag.next = l1;
flag = flag.next;
l1 = l1.next;
}
else{
flag.next = l2;
flag = flag.next;
l2 = l2.next;
}
}
while(l1 != null){
flag.next = l1;
flag = flag.next;
l1 = l1.next;
}
while(l2 != null){
flag.next = l2;
flag = flag.next;
l2 = l2.next;
}
return res.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: