赞
踩
https://leetcode-cn.com/problems/merge-two-sorted-lists/description/
合并两条有序链表,形成一条新的有序链表:用递归实现
1.如果其中一条链表为空,那么只需要接上(返回)另一条链表即可
2.两条链表都不为空的话就比较两条链当前位置的值大小。左链小,就用小值创建一个新结点到合并链上,合并链的下一个结点则递归调用函数合并除掉已添加的点后的两条链表
- /**
- * Definition for singly-linked list.
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode(int x) { val = x; }
- * }
- */
- class Solution {
-
- public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
-
- if(l1 == null)
- return l2;
- if(l2 == null)
- return l1;
- if(l1.val <= l2.val) {
- ListNode l3 = new ListNode(l1.val);
- l3.next = mergeTwoLists(l1.next,l2);
- } else {
- ListNode l3 = new ListNode(l2.val);
- l3.next = mergeTwoLists(l1,l2.next);
- }
- return l3;
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。