1 题目:
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.
2 思路:
这个就是归并排序的重新排好两个已经排好序的那个步骤。
好吧,这是第一个一次accped的题目。。
3 代码:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1 == null){ return l2; } if(l2 == null){ return l1; } ListNode head = new ListNode(0); ListNode node = head; ListNode list1 = l1; ListNode list2 = l2; while(list1 != null && list2 != null){ if(list1.val > list2.val){ node.next = list2; list2 = list2.next; }else{ node.next = list1; list1 = list1.next; } node = node.next; } /* connect the longer list */ while(list1 != null){ node.next = list1; list1 = list1.next; node = node.next; } while(list2 != null){ node.next = list2; list2 = list2.next; node = node.next; } return head.next; }
看了https://leetcode.com/discuss/16346/java-solution-for-reference 的代码,发现最后两个只要接上链表就行了,不用再遍历一遍了。
也就是:
if (l1 != null) { node.next = list1; } if (l2 != null) { node.next = list2; }