题解 | #合并有序链表#
合并有序链表
http://www.nowcoder.com/practice/a479a3f0c4554867b35356e0d57cf03d
此文仅用于本人学习记录
注意判断是 l 负责的,ptr 只是跑腿的。还有就是这题没说构造函数,我以为 new TreeNode()就行的。
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param l1 ListNode类 * @param l2 ListNode类 * @return ListNode类 */ public ListNode mergeTwoLists (ListNode l1, ListNode l2) { // write code here ListNode resultIter = new ListNode(0);//这里有点坑 ListNode resultHead = resultIter; ListNode ptr1 = l1; ListNode ptr2 = l2; while(l1 != null && l2 != null){ if(l1.val < l2.val){ l1 = l1.next; ptr1.next = null; resultIter.next = ptr1; resultIter = resultIter.next; ptr1 = l1; } else { l2 = l2.next; ptr2.next = null; resultIter.next = ptr2; resultIter = resultIter.next; ptr2 = l2; } } if(l1 != null){ resultIter.next = l1; } if(l2 != null){ resultIter.next = l2; } return resultHead.next; } }