题目:
将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
解法一:递归
public ListNode mergeTwoLists(ListNode list1, ListNode list2) { if (null == list1) return list2; if (null == list2) return list1; if (list1.val < list2.val) { list1.next = mergeTwoLists(list1.next, list2); return list1; } list2.next = mergeTwoLists(list1, list2.next); return list2; }
测试
public static void main(String[] args) { ListNode l1 = ListNode.build(new int[]{1, 2, 4, 6}); ListNode l2 = ListNode.build(new int[]{1, 3, 4}); new LC_0021().mergeTwoLists(l1, l2).display(); }
解法二:for循环+双指针
public ListNode mergeTwoLists(ListNode list1, ListNode list2) { ListNode res = new ListNode(); ListNode tail = res; if (null == list1) return list2; if (null == list2) return list1; while (null != list1 && null != list2) { if (list1.val < list2.val) { tail.next = list1; list1 = list1.next; } else { tail.next = list2; list2 = list2.next; } tail = tail.next; } if (null != list1) tail.next = list1; if (null != list2) tail.next = list2; return res.next; }
标签:null,ListNode,合并,list1,tail,list2,链表,算法,next From: https://www.cnblogs.com/dork-h/p/16709084.html