zoukankan      html  css  js  c++  java
  • [LintCode] Merge Two Sorted Lists

     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.

    Example

    Given 1->3->8->11->15->null2->null , return 1->2->3->8->11->15->null.

    Key idea:

    1. Use a dummy node to simplify head node management;

    2. Apply the merge procedure in merge sort.

     1 /**
     2  * Definition for ListNode.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int val) {
     7  *         this.val = val;
     8  *         this.next = null;
     9  *     }
    10  * }
    11  */
    12 
    13 
    14 public class Solution {
    15     /*
    16      * @param l1: ListNode l1 is the head of the linked list
    17      * @param l2: ListNode l2 is the head of the linked list
    18      * @return: ListNode head of linked list
    19      */
    20     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    21         if(l1 == null) {
    22             return l2;
    23         }
    24         else if(l2 == null) {
    25             return l1;
    26         }
    27         ListNode dummy = new ListNode(0);
    28         ListNode curr = dummy, curr1 = l1, curr2 = l2, temp = null;
    29         while(curr1 != null && curr2 != null) {
    30             if(curr1.val <= curr2.val) {
    31                 curr.next = curr1;
    32                 temp = curr1.next;
    33                 curr1.next = null;
    34                 curr1 = temp;
    35             }
    36             else {
    37                 curr.next = curr2;
    38                 temp = curr2.next;
    39                 curr2.next = null;
    40                 curr2 = temp;
    41             }
    42             curr = curr.next;
    43         }
    44         if(curr1 != null) {
    45             curr.next = curr1;
    46         }
    47         else if(curr2 != null) {
    48             curr.next = curr2;
    49         }
    50         return dummy.next;
    51     }
    52 }

    Related Problems

    Merge Two Sorted Arrays

  • 相关阅读:
    jeecg+activemq之AjaxServlet+tomcat7
    odoo8.0 win7 64位 安装配置(补遗)
    odoo种种
    MySQL种种
    html种种
    jQuery种种
    freemarker种种
    jQuery ui autocomplete 与easyUI冲突解决办法(重命名ui的autocomplete 和menu部分)
    vue实现点击按钮下载图片
    VUE父子组件之间的传值,以及兄弟组件之间的传值
  • 原文地址:https://www.cnblogs.com/lz87/p/7497000.html
Copyright © 2011-2022 走看看