输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
1 # -*- coding:utf-8 -*- 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 class Solution: 7 # 返回合并后列表 8 def Merge(self, pHead1, pHead2): 9 if pHead1 == None: 10 return pHead2 11 if pHead2 == None: 12 return pHead1 13 if pHead1.val <= pHead2.val: 14 pHead1.next = self.Merge(pHead1.next,pHead2) 15 return pHead1 16 else: 17 pHead2.next = self.Merge(pHead1,pHead2.next) 18 return pHead2 19 # write code here
leetcode地址,java版代码:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 class Solution { 10 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 11 if(l1 == null){ 12 return l2; 13 } 14 if(l2 == null){ 15 return l1; 16 } 17 if(l1.val <= l2.val){ 18 l1.next = mergeTwoLists(l1.next,l2); 19 return l1; 20 }else{ 21 l2.next = mergeTwoLists(l1,l2.next); 22 return l2; 23 } 24 } 25 }