/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution { public ListNode MergeTwoLists(ListNode l1, ListNode l2) { //递归实现链表合并 ListNode l = null; if (l1 == null && l2 != null) { return l2; } else if (l2 == null && l1 != null) { return l1; } else if (l1 == null && l2 == null) { return null; } else { if (l1.val < l2.val) { if (l == null) { l = l1; } l.next = MergeTwoLists(l1.next, l2); } else { if (l == null) { l = l2; } l.next = MergeTwoLists(l1, l2.next); } return l; } } }
https://leetcode.com/problems/merge-two-sorted-lists/#/description
补充一个python的实现:
1 class Solution: 2 def mergeTwoLists(self, l1: 'ListNode', l2: 'ListNode') -> 'ListNode': 3 if l1 == None: 4 return l2 5 if l2 == None: 6 return l1 7 if l1.val < l2.val: 8 l1.next = self.mergeTwoLists(l1.next,l2) 9 return l1 10 else: 11 l2.next = self.mergeTwoLists(l2.next,l1) 12 return l2
python非递归写法:
1 class Solution: 2 def mergeTwoLists(self, l1, l2): 3 prehead = ListNode(-1) 4 prev = prehead 5 while l1 and l2: 6 if l1.val <= l2.val: 7 prev.next = l1 8 l1 = l1.next 9 else: 10 prev.next = l2 11 l2 = l2.next 12 prev = prev.next 13 14 # 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可 15 prev.next = l1 if l1 is not None else l2 16 17 return prehead.next