LinkedList - 21. Merge Two Sorted Lists

时间:2022-07-25
本文章向大家介绍LinkedList - 21. Merge Two Sorted Lists,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

思路:

合并两个有序链表,做法有两种,递归和迭代,递归的条件就是返回两个节点中小的那个节点。迭代就是正常遍历,然后比较两个链表的节点,生成新的合并链表。

代码:

java:

/**

 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution { 
   /* // recursion
    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);
        else l2.next = mergeTwoLists(l1, l2.next);
        
        return l1.val < l2.val ? l1 : l2;
    }*/
    
    // iteratively
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode result = null;
        ListNode temp = null; 
        
        while(l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                if (result == null) {
                    result = l1;
                    temp = l1;
                } else {
                    temp.next = l1;
                    temp = l1;
                }
                l1 = l1.next;
            } else {
                if (result == null) {
                    result = l2;
                    temp = l2;
                } else {
                    temp.next = l2;
                    temp = l2;
                }
                l2 = l2.next;
            }
        }
        
        if (l1 != null) {
            if (result == null) {
                result = l1;
            } else {
                temp.next = l1;
            }
        
        } else {
            if (result == null) {
                result = l2;
            } else {
                temp.next = l2;
            }
        }
        
        return result;
    }
}