leetcode——21. 合并两个有序链表

 

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        p=rst=ListNode(0)
        while True:
            try:
                while l1.val<=l2.val:
                    p.next=l1
                    l1,p=l1.next,p.next
                while l1.val>l2.val:
                    p.next=l2
                    l2,p=l2.next,p.next
            except:break
        p.next=l1 or l2
        return rst.next
执行用时 :44 ms, 在所有 python3 提交中击败了95.09%的用户
内存消耗 :13.9 MB, 在所有 python3 提交中击败了5.66%的用户
 
                                                                                                         ——2019.10.23

 


 

复习:

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l2 == null){
            return l1;
        }else if(l1 == null){
            return l2;
        }
        ListNode node = new ListNode(-1);
        ListNode head = node;
        while(l1 != null && l2 != null){
            if(l1.val > l2.val){
                node.next = new ListNode(l2.val);
                node = node.next;
                l2 = l2.next;
            }else{
                node.next = new ListNode(l1.val);
                node = node.next;
                l1 = l1.next;
            }
        }
        if(l1 != null){
            node.next = l1;
        }
        if(l2 != null){
            node.next = l2;
        }
        return head.next;
    }

 

 

 ——2020.7.3


方法二:

递归:

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

 

posted @ 2019-10-23 19:37  欣姐姐  阅读(174)  评论(0编辑  收藏  举报