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;
}
}
果然一做链表的题逻辑很清楚,就是这个写起来就很乱。
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;
}
}
相关文章推荐
- [LintCode 104] 合并k个排序链表(Python)
- lintcode-合并k个排序链表-104
- lintcode-104-合并k个排序链表
- 用最小堆将k个已排序链表合并为一个排序链表
- 合并k个排序链表
- [Leetcode] Merge k sorted lists 合并k个已排序的链表
- LintCode-分治-合并k个排序链表
- 合并k个排序链表
- lintcode merge-k-sorted-lists 合并k个排序链表
- 合并k个已排序的链表
- 第六章堆排序之“用最小堆将k个已排序链表合并为一个排序链表”(练习6.5-8)
- 合并k个排序链表,lintcode
- LintCode--合并k个排序链表
- 合并k个排序链表
- [各种面试题] 合并k个排序链表
- 链表——合并K个排序的链表
- 堆排序之“用最小堆将k个已排序链表合并为一个排序链表”
- leetcode 23. Merge k Sorted Lists 合并k个排序链表 优先级队列
- 第六章堆排序之“用最小堆将k个已排序链表合并为一个排序链表”(练习6.5-8)
- 题目:合并k个排序链表