Merge Two Sorted Lists

来源:互联网 发布:手机淘宝怎么设置心选 编辑:程序博客网 时间:2024/05/14 10:36
  1. 题目
    Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.
    将两个排序链表合并为一个新的排序链表

  2. 算法
    这一题和Merge Sorted Array差不多,用一个链表节点pre表示当前链表节点的上一个节点,我们用helper表示要求链表的虚头节点,我们将helper的下一个节点指向l1的第一个节点步骤如下
    1 比较l1和l2值的大小,如果l1值大于l2值,将当前节点(pre.next)指向l2,之后再回来指向l1,此时l2移向下一节点;如果l1小于l2的值,应为目标一直指向的是l1,只把l1后移就行。
    2 最后当l2还剩有值时,只把pre.next指向l2就行

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {        // write your code here        ListNode helper = new ListNode(0); //虚节点        ListNode pre = helper;        helper.next = l1;       //结果指向l1        while (l1 != null && l2 != null) {            if (l1.val > l2.val) {    //当l2值大于l1值时                ListNode next = l2.next;   // 保存l2的下节点1                l2.next = pre.next;        //包村l1节点,pre.next指向l1  2                pre.next = l2;   //将l2节点赋予当前节点 和2 一起又将下节点指向l1                l2 = next;      //1一起将l2挪下一节点            } else {                l1 = l1.next;  //目标一直指向l1节点,不用变换            }            pre = pre.next;        }        if (l2 != null) {            pre.next = l2;        }        return helper.next;    }
0 0
原创粉丝点击