码迷,mamicode.com
首页 > 编程语言 > 详细

合并两个排序的链表

时间:2016-08-29 22:13:47      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

思路:可以有两种实现方法,第一种是通过递归来实现,第二种是通过非递归来实现。

public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null && list2 == null){
            return null;
        }
        if(list1 == null && list2!=null){
            return list2;
        }
        if(list1!=null&&list2==null){
            return list1;
        }
        ListNode merge = null;
        if(list1.val <list2.val){
            merge = list1;
            merge.next = Merge(list1.next,list2);            
        }else{
            merge = list2;
            merge.next = Merge(list1,list2.next);
        }
        return merge;
    }
}

非递归:

public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null && list2 == null){
            return null;
        }
        if(list1 == null && list2!=null){
            return list2;
        }
        if(list1!=null&&list2==null){
            return list1;
        }
        ListNode merge = null;
        ListNode merge2 = null;
        while(list1!=null &&list2!=null){
            if(list1.val<list2.val){
                if(merge == null){
                    merge2 = merge = list1; //确保头节点
                }else{
                    merge.next = list1;
                    merge = merge.next;
                }
                list1 = list1.next;
            }else{
                if(merge == null){
                    merge2 = merge = list2;
                }else{
                    merge.next = list2;
                    merge = merge.next; //这个也要移位
                }
                list2 = list2.next;
            }
        }
        if(list1!=null){
            merge.next = list1; //节点赋值即可
        }
        if(list2!=null){
            merge.next = list2;
        }
        return merge2;
    }

  

合并两个排序的链表

标签:

原文地址:http://www.cnblogs.com/yingpu/p/5819613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!