美文网首页
合并两个链表

合并两个链表

作者: 言的希 | 来源:发表于2021-09-07 11:28 被阅读0次

    输入两个递增排序的链表,合并这两个链表并使这两个链表中的节点交叉相叠。

    示例1:

            输入:1->3->4, 1->2->4

            输出:1->1->3->2->4->4

    解决思路:1>迭代法

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

            if(l1 == null) {

                return l2;

            }

            if(l2 == null) {

                return l1;

            }

            ListNode head = l1;

            ListNode temp1 = l1.next;

            ListNode temp2 = l2.next;

            l1.next = l2;

            l1.next.next = temp1;

            l1 = l1.next.next;

            while(l1 != null) {

                temp1 = l1.next;

                l1.next = temp2;

                temp2 = l1.next.next;

                l1.next.next = temp1;

                l1 = l1.next.next;

            }

            return head;

        }

    2>递归法:

    public ListNodemergeTwoLists(ListNode l1, ListNode l2) {

        if(l1==null) {

            return l2;

        }

        if(l2==null) {

            return l1;

        }

        l1.next = mergeTwoLists(l2, l1.next);

        return l1;

    }

    相关文章

      网友评论

          本文标题:合并两个链表

          本文链接:https://www.haomeiwen.com/subject/zkguwltx.html