More:【目录】LeetCode Java实现html
https://leetcode.com/problems/merge-two-sorted-lists/java
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.node
Example:post
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
与合并两个排序的链表题目彻底相同,能够采用循环和递归来实现。循环的实现代码中能够使用一个dummyHead(虚假头结点),这个结点能够简化代码(不用先算出头结点了,并且一开始不须要判断List1和List2为null了)。ui
(有了dummy以后,全部的节点都变成拥有前置节点的节点了。因此就不用担忧处理头节点这个特殊状况了。并且你最后须要返回的仅仅是dummy.next,不用花功夫去保持住你的头结点了)url
(We insert a dummy head before the new list so we don’t have to deal with special cases such as initializing the new list’s head. Then the new list’s head could just easily be returned as dummy head’s next node.)code
//1. 循环 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { //有了dummyHead,就不须要下面两句了,并且也不用在l1和l2中找出头结点, //头结点直接用dummyHead.next表示。 //if(l1==null) return l2; //if(l2==null) return l1; ListNode dummyHead=new ListNode(0); ListNode p=dummyHead; while(l1!=null && l2!=null){ if(l1.val<l2.val){ p.next=l1; l1=l1.next; }else{ p.next=l2; l2=l2.next; } p=p.next; } p.next= l1==null? l2:l1; return dummyHead.next; } //2. 递归 public ListNode mergeTwoLists2(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; } }
1. 学会使用dummyHead,注意dummyHead必须初始化,不能为null。htm
More:【目录】LeetCode Java实现blog