合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4] 输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = [] 输出:[]
示例 3:
输入:l1 = [], l2 = [0] 输出:[0]
提示:
两个链表的节点数目范围是 [0, 50] -100 <= Node.val <= 100 l1 和 l2 均按 非递减顺序 排列
方法一:迭代
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11 class Solution { 12 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 13 if (l1 == null) return l2; 14 if (l2 == null) return l1; 15 16 // 头结点 17 ListNode head; 18 if (l1.val <= l2.val) { 19 head = l1; 20 l1 = l1.next; 21 } else { 22 head = l2; 23 l2 = l2.next; 24 } 25 26 ListNode cur = head; 27 while (l1 != null && l2 != null) { 28 if (l1.val <= l2.val) { 29 cur = cur.next = l1; 30 l1 = l1.next; 31 } else { 32 cur = cur.next = l2; 33 l2 = l2.next; 34 } 35 } 36 37 if (l1 == null) { 38 cur.next = l2; 39 } else if (l2 == null) { 40 cur.next = l1; 41 } 42 return head; 43 } 44 }
方法二:利用虚拟头结点
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; // 虚拟头结点 ListNode head = new ListNode(0); ListNode cur = head; while (l1 != null && l2 != null) { if (l1.val <= l2.val) { cur = cur.next = l1; l1 = l1.next; } else { cur = cur.next = l2; l2 = l2.next; } } if (l1 == null) { cur.next = l2; } else if (l2 == null) { cur.next = l1; } return head.next; } }
方法三:递归
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 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; } } }

浙公网安备 33010602011771号