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

    Link:http://oj.leetcode.com/problems/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         if (l1 == null)
    15             return l2;
    16         if (l2 == null)
    17             return l1;
    18         ListNode head = new ListNode(0);
    19         ListNode result = head;
    20         while (l1 != null && l2 != null) {
    21             if (l1.val > l2.val) {
    22                 result.next = new ListNode(l2.val);
    23                 result = result.next;
    24                 l2 = l2.next;
    25             } else {
    26                 result.next = new ListNode(l1.val);
    27                 result = result.next;
    28                 l1 = l1.next;
    29             }
    30         }
    31         if (l1 != null)
    32             result.next = l1;
    33         if (l2 != null)
    34             result.next = l2;
    35 
    36         result = head.next;
    37         return result;
    38     }
    39 }

    没啥好说的。就是感觉代码不够decent。。循环中也可以不开新的空间。。

  • 相关阅读:
    hdu 1104 数论+bfs
    hdu 1019 最小公倍数
    hdu 1005 数论 循环
    山东省第三届acm
    hdu 1576
    浏览器支持
    FormData
    获取APP图片资源
    链接转标签
    bug20170125
  • 原文地址:https://www.cnblogs.com/Altaszzz/p/3703539.html
Copyright © 2011-2022 走看看