21. Merge Two Sorted Lists

来源:互联网 发布:澳门mac专柜 编辑:程序博客网 时间:2024/05/22 05:33

题目

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.

我的解法

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    //合并l1、l2链表     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        // 假的头节点,方便后续插入        ListNode fakeHead = new ListNode(-1);        ListNode prev = fakeHead;        while(l1 != null || l2 != null){            // 如果l1、l2有一个为null,则把非空链表插入合并链表后即可            if(l1 == null){                prev.next = l2;                break;            }            if(l2 == null){                prev.next = l1;                break;            }            // 将较小值得节点插入合并链表中            if(l1.val < l2.val){                prev.next = l1;                prev = l1;                l1 = l1.next;            }else{                prev.next = l2;                prev = l2;                l2 = l2.next;            }        }        return fakeHead.next;    }}

算法分析:对两链表迭代求解,通过比较两节点来判断插入哪个。

答案解法(递归求解)

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    //合并l1、l2链表     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        // l1 l2有一链表为空时,返回另一链表        if(l1 == null)            return l2;        if(l2 == null)            return l1;        ListNode head = null;        // 头节点为l1、l2较小值的节点        if(l1.val < l2.val){            head = l1;            l1 = l1.next;        }else{            head = l2;            l2 = l2.next;        }        // 头节点插入子链表合成结果        head.next = mergeTwoLists(l1, l2);        return head;    }}

算法分析:函数的功能是合并l1、l2链表;先合并一个节点,节点的子链表为l1子链表和l2子链表的合并结果,即可通过递归解决。
0 0