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

    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.

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    14         
    15             if (l1==null || l2==null) {
    16                 if (l1 != null) {
    17                     return l1;
    18                 }
    19                 if (l2 != null) {
    20                     return l2;
    21                 }
    22                 return null;
    23             }
    24             ListNode first;
    25             ListNode curr;
    26             if (l1.val < l2.val) {
    27                 curr=l1;
    28                 l1=l1.next;
    29             }else {
    30                 curr=l2;
    31                 l2=l2.next;
    32             }
    33             first=curr;
    34             while (l1!=null && l2!=null) {
    35                 if (l1.val<l2.val) {
    36                     curr.next=l1;
    37                     l1=l1.next;
    38                     curr=curr.next;
    39                 }else {
    40                     curr.next=l2;
    41                     l2=l2.next;
    42                     curr=curr.next;
    43                 }
    44             }
    45             if (l1!=null) {
    46                 curr.next=l1;
    47             }
    48             if (l2!=null) {
    49                 curr.next=l2;
    50             }
    51             return first;
    52     }
    53 }
  • 相关阅读:
    2019.1.1-11 总结
    配置文件的选择
    2019.1.1-5 总结
    shell 脚本
    2017- 感谢自己
    debug和release版本的区别
    linux 下一些命令
    Python中getopt()函数的使用
    开发环境的一些基本认识
    Leetcode 49. Group Anagrams
  • 原文地址:https://www.cnblogs.com/birdhack/p/3992337.html
Copyright © 2011-2022 走看看