【leetcode】【21】Merge Two Sorted Lists

来源:互联网 发布:喷绘设计用什么软件 编辑:程序博客网 时间:2024/05/04 17:37

一、问题描述

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.

二、问题分析

两个有序链表的合并,这是数据结构链表处必讲的一道题。无非就是两个链表依次比较大小,小的插入新的链表,时间复杂度O(m+n)。也可以采用递归。

三、Java AC 代码

普通
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        if (null==l1) {return l2;} if (null==l2) {return l1;}ListNode virtulHead = new ListNode(0);ListNode current = virtulHead;        ListNode p = l1;        ListNode q = l2;        while(p!=null && q!=null){        if (p.val<q.val) {        current.next = p;p = p.next;current = current.next;} else {current.next = q;q = q.next;current = current.next;}        }        if (p!=null) {current.next = p;}        if (q!=null) {current.next = q;}        return virtulHead.next;    }


递归
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        if (null==l1) {return l2;} if (null==l2) {return l1;}ListNode virtulHead ;if (l1.val<l2.val) {virtulHead = l1;virtulHead.next = mergeTwoLists(l1.next, l2);} else {virtulHead = l2;virtulHead.next = mergeTwoLists(l1, l2.next);}                return virtulHead;    }


0 0