LeetCode21. 合并两个有序链表
解法:本题同剑指16.合并两个排序的链表
class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { /** * 解法1: 非递归 */ ListNode dummyHead = new ListNode(-1); ListNode cur = dummyHead; while (l1 != null && l2 != null) { if (l1.val < l2.val) { cur.next = l1; l1 = l1.next; }else { cur.next = l2; l2 = l2.next; } cur = cur.next; // 更新当前节点,使其始终指向合并链表的尾部 } if (l1 != null) cur.next = l1; if (l2 != null) cur.next = l2; return dummyHead.next; /** * 解法2:递归 * 较小节点的next指针指向其余节点的合并结果 * 递归到底后,逐层返回每一层调用排序好的链表头 */ /* if (l1 == null) return l2; if (l2 == null) return l1; if (l1.val < l2.val) { l1.next = mergeTwoLists(l1.next, l2); return l1; }else { l2.next = mergeTwoLists(l1, l2.next); return l2; } */ } }
参考题解: