[leetcode]21.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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

解法一

思路

两个链表合并,思路很简单,先新建一个新的链表,然后比较两个链表的元素值,把较小的链表结点放到新链表中,然后继续比较。由于两个链表的长度可能不同,最终可能出现还不为空的链表,此时直接将其接到新链表最后即可。

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode cur;
        ListNode res;
        if(l2 == null) return l1;
        else if(l1 == null) return l2;
        else{
            if(l1.val <= l2.val) {
                cur = l1;
                l1 = l1.next;
            }else{
                cur = l2;
                l2 = l2.next;
            }
            res = cur;
            while(l1 != null && l2 != null) {
                if(l1.val <= l2.val) {
                    cur.next = l1;
                    l1 = l1.next;
                    cur = cur.next;
                }else{
                    cur.next = l2;
                    l2 = l2.next;
                    cur = cur.next;
                }
            }
            if(l1 != null) cur.next = l1;
            else cur.next = l2;
        }
        return res;
    }
}

解法二

思路

还有一种递归的方法,如果l1的值小,那么对于l1的next和l2进行合并,然后将返回值赋给l1.next,然后返l1;反之同理。

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        if(l1.val <= l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }
}
posted @ 2018-09-29 09:06  shinjia  阅读(79)  评论(0编辑  收藏  举报