• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

方法二(推荐方法1): 

新的Linkedlist不以任何现有List为依托,维护一个dummmy node和当前节点ListNode cur,把两个list的元素往里面插入作为cur.next,每次不new一个新的ListNode, 而是用已有的。相较于法一最后需要讨论两个list各自没有走完的情况

 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 class Solution {
10     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
11         ListNode dummy = new ListNode(-1);
12         ListNode cur = dummy;
13         while (l1 != null && l2 != null) {
14             if (l1.val <= l2.val) {
15                 cur.next = l1;
16                 l1 = l1.next;
17             }
18             else {
19                 cur.next = l2;
20                 l2 = l2.next;
21             }
22             cur = cur.next;
23         }
24         cur.next = l1 != null ? l1 : l2;
25         return dummy.next;
26     }
27 }

 

方法三:(推荐方法2)Recursion

 1 public ListNode mergeTwoLists(ListNode l1, ListNode l2){
 2         if(l1 == null) return l2;
 3         if(l2 == null) return l1;
 4         if(l1.val < l2.val){
 5             l1.next = mergeTwoLists(l1.next, l2);
 6             return l1;
 7         } else{
 8             l2.next = mergeTwoLists(l1, l2.next);
 9             return l2;
10         }
11 }

 

 

 

posted @ 2014-05-09 03:38  neverlandly  阅读(819)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3