题目在这里: https://leetcode.com/problems/merge-two-sorted-lists/
【标签】Linked List
【题目分析】这个题目就是merge sort在 Linked List中的变形。不多说,直接上代码了
1 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 2 ListNode dummyHead = new ListNode(-1); 3 ListNode node = dummyHead; 4 while (l1 != null && l2 != null) { 5 if (l1.val <= l2.val) { 6 node.next = l1; 7 l1 = l1.next; 8 } else { 9 node.next = l2; 10 l2 = l2.next; 11 } 12 node = node.next; 13 } 14 // append the remaining list 15 node.next = (l1 != null) ? l1 : l2; 16 return dummyHead.next; 17 }
时间: 2024-10-05 09:31:18