8.17 可以自己 A 出来


第一次复习
9.15 可以自己 A 出来

题目描述


力扣:https://leetcode-cn.com/problems/merge-two-sorted-lists/

剑指:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/

解题思路


K神题解:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/solution/

  1. class Solution {
  2. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  3. ListNode res = new ListNode(0); // 创建一个头节点
  4. ListNode tmp = res; // 维护一个指针指向头节点,操作此指针也就操作了新建的链表
  5. while(l1 != null && l2 != null) {
  6. if(l1.val <= l2.val) {
  7. tmp.next = l1;
  8. l1 = l1.next;
  9. }else {
  10. tmp.next = l2;
  11. l2 = l2.next;
  12. }
  13. tmp = tmp.next;
  14. }
  15. tmp.next = l1 == null ? l2 : l1;
  16. return res.next;
  17. }
  18. }