比较基础的链表题,精髓在于使用dummy节点来方便的维护链表头。
public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); ListNode temp = dummy; while(l1 != null && l2 != null) { if(l1.val < l2.val) { temp.next = l1; temp = temp.next; l1 = l1.next; } else { temp.next = l2; temp = temp.next; l2 = l2.next; } } temp.next = l1 == null ? l2 : l1; return dummy.next; } }
没有评论:
发表评论