【LeetCode21】【Merge Two Sorted Lists】递归实现

xiaoxiao2021-02-27  333

题目原文:

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.

题意理解:

题目的意思是说把两个排好序的list,合并成一个新的排好序的list,并返回。例如:input:[1,3,5][2,4];output:[1,2,3,4,5].

代码:

java递归实现代码:

实现思路:每次递归返回两个节点中值较小的那个节点,直到其中一个节点为null时返回最后一个最大的节点结束递归

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1==null){ return l2; } if(l2==null){ return l1; } ListNode mergeNode; if(l1.val<l2.val){ mergeNode = l1; mergeNode.next = mergeTwoLists(l1.next,l2); }else{ mergeNode = l2; mergeNode.next = mergeTwoLists(l1,l2.next); } return mergeNode; }
转载请注明原文地址: https://www.6miu.com/read-5477.html

最新回复(0)