zoukankan      html  css  js  c++  java
  • 21. Merge Two Sorted Lists Java solutions

    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.

    Subscribe to see which companies asked this question

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    11         if(l1 == null) return l2;
    12         if(l2 == null) return l1;
    13         ListNode res = new ListNode(-1);
    14         ListNode pre = new ListNode(-1);
    15         res.next = pre;
    16         while(l1!= null && l2 != null){
    17             if(l1.val <= l2.val){
    18                 pre.next = l1;
    19                 l1 = l1.next;
    20             }else{
    21                 pre.next = l2;
    22                 l2 = l2.next;
    23             }
    24             pre = pre.next;
    25         }
    26         if(l1 != null) pre.next = l1;
    27         if(l2 != null) pre.next = l2;
    28         return res.next.next;
    29     }
    30 }
  • 相关阅读:
    系统安全及应用
    进程和计划任务管理
    Java技术体系
    开机十步和进程管理
    Raid
    LVM逻辑卷
    sed命令
    磁盘管理
    你的背景,是这个时代 张璁
    别将梦想停留在二十岁
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5417059.html
Copyright © 2011-2022 走看看