合并两个有序链表,第一个想法就是归并排序。

java实现代码如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        
        ListNode listNode = new ListNode(0);
        ListNode temp = listNode;
        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;
            }
        }
        
        while(l1 != null){
            temp.next = l1;
            temp = temp.next;
            l1 = l1.next;
        }
        while(l2 != null){
            temp.next = l2;
            temp = temp.next;
            l2 = l2.next;
        }
        
        return listNode.next;
    }
}

执行效果:

LeetCode-合并两个有序链表

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-06
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-07-16
  • 2022-12-23
  • 2022-12-23
  • 2021-10-11
  • 2021-06-04
  • 2021-07-31
  • 2021-08-31
相关资源
相似解决方案