首页 > 代码库 > Merge Two Sorted Lists

Merge Two Sorted Lists

https://oj.leetcode.com/problems/merge-two-sorted-lists/

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.

解题思路:

这道题比较基础,和数组的归并排序类似。可以考虑一个全新的待构建的mergedList,首先初始化他的首节点为l1和l2中较小的那个。当然,这之前必须判断l1和l2的null情况,可直接return。然后l1和l2往后迭代,并将mergedList的next指向他们中间较小的节点,同时将mergedList往后移动一个,同时l1和l2中较小的那个节点也向后移动一个。如此往复,直到l1或l2有一个到达结尾。

最后,将l1和l2剩下的一段(即较长的),直接接在mergedList最后。返回mergedList,当然这里返回的是开始预留的指向首节点的引用,因为这时的节点已经指向结尾。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        if(l1 == null){            return l2;        }        if(l2 == null){            return l1;        }                //可以看作是一个新的mergedlist,用来被构建        ListNode listNode;        //初始化listNode的第一个节点        if(l1.val < l2.val){            listNode = l1;            l1 = l1.next;        }else{            listNode = l2;            l2 = l2.next;        }        //留作返回的headNode,因为上面的listNode要不断往后迭代        ListNode headNode = listNode;                while(l1 != null && l2 != null){            if(l1.val < l2.val){                listNode.next = l1;                listNode = listNode.next;                l1 = l1.next;            }else{                listNode.next = l2;                listNode = listNode.next;                l2 = l2.next;            }        }        //l1或l2比较长的那个,剩下节点直接接在结果list的后面        if(l1 == null){            listNode.next = l2;        }        if(l2 == null){            listNode.next = l1;        }        return headNode;    }}

 

Merge Two Sorted Lists