Merge Two Sorted Lists
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.
思路: 新生成的链表指向第一条链表
java代码:
- public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
- if(l1==null) return l2;
- if(l2==null) return l1;
- ListNode dummy = new ListNode(-1);
- ListNode p=dummy;
- p.next = l1;
- while(l1!=null&&l2!=null) {
- if(l2.val < l1.val) {
- p.next = l2;
- l2 = l2.next;
- } else {
- l1 = l1.next;
- }
- p = p.next;
- p.next = l1;
- }
- if(l2!=null) {
- p.next = l2;
- }
- return dummy.next;
- }

浙公网安备 33010602011771号