码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode 21] Merge Two Sorted Lists

时间:2015-09-05 00:08:47      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

 1 题目:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

2 思路:

这个就是归并排序的重新排好两个已经排好序的那个步骤。

好吧,这是第一个一次accped的题目。。

 

3 代码:

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null){
            return l2;
        }
        if(l2 == null){
            return l1;
        }
        ListNode head = new ListNode(0);
        ListNode node = head;
        
        ListNode list1 = l1;
        ListNode list2 = l2;
    
        while(list1 != null && list2 != null){
            if(list1.val > list2.val){
                node.next = list2;
                list2 = list2.next;
            }else{
                node.next = list1;
                list1 = list1.next;
            }
            node = node.next;
        }
        
        /* connect the longer list */
        while(list1 != null){
            node.next = list1;
            list1 = list1.next;
            node = node.next;
        }
        while(list2 != null){
            node.next = list2;
            list2 = list2.next;
            node = node.next;
        }
        
        return head.next;
    }

 看了https://leetcode.com/discuss/16346/java-solution-for-reference 的代码,发现最后两个只要接上链表就行了,不用再遍历一遍了。

也就是:

        if (l1 != null) {
            node.next = list1;
        }
        if (l2 != null) {
            node.next = list2;
        }

 

[leetcode 21] Merge Two Sorted Lists

标签:

原文地址:http://www.cnblogs.com/lingtingvfengsheng/p/4782473.html

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