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.
Example:
1 2
|
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
|
合并两条已排序的链表,返回新链表,新链表必须包含两个链表的所有节点。
分析:涉及到头节点的操作,删除或者更改新增,都可以考虑创建一个dummy = new ListNode(0),最后返回dummy.next,逻辑上不容易出错。详细代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
class { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); ListNode head = dummy; while (l1 != null && l2 != null) { if (l1.val < l2.val) { head.next = l1; l1 = l1.next; } else { head.next = l2; l2 = l2.next; } head = head.next; } if (l1 != null) { head.next = l1; l1 = l1.next; } if (l2 != null) { head.next = l2; l2 = l2.next; } return dummy.next; } }
|
近期评论