本文共 1389 字,大约阅读时间需要 4 分钟。
问题:
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.
官方难度:
Easy
翻译:
合并2个已排序的链表,得到一个新的链表并且返回其第一个节点。
解题代码:
1 public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { 2 if (l1 == null) { 3 return l2; 4 } 5 if (l2 == null) { 6 return l1; 7 } 8 // 返回的第一个节点 9 ListNode first = l1.val > l2.val ? l2 : l1;10 // 上一个节点11 ListNode last = new ListNode(0);12 while (true) {13 if (l1.val > l2.val) {14 // 交换l1节点和l2节点,保证下一次循环仍然以l1节点为基准15 ListNode swapNode = l2;16 l2 = l1;17 l1 = swapNode;18 }19 // 将last节点的next指针指向l1,同时更新last20 last.next = l1;21 last = l1;22 // 带排序的链表遍历完成,剩余链表自然有序23 if (l1.next == null) {24 l1.next = l2;25 break;26 }27 l1 = l1.next;28 }29 return first;30 }
相关链接:
PS:如有不正确或提高效率的方法,欢迎留言,谢谢!
转载地址:http://soyyz.baihongyu.com/