(Java)LeetCode-21. Merge Two Sorted Lists

原创 2016年05月31日 14:59:27

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.


这道题和之前的合并已排序的数组的思路一样的,就是变成了链表而已,稍稍复杂一点。


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode list = new ListNode(-2);
        ListNode head = list;
        
        while(l1 != null || l2 != null){
        	if(l1 == null){
        		list.next = l2;
        		return head.next;
        	}else if( l2 == null){
        		list.next = l1;
        		return head.next;
        	}else if(l1.val >= l2.val){
        		ListNode next = new ListNode(l2.val);
        		list.next = next;
        		list = next;
        		l2 = l2.next;
        	}else{
        		ListNode next = new ListNode(l1.val);
        		list.next = next;
        		list = next;
        		l1 = l1.next;
        	}
        }
		return head.next;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode 21 Merge Two Sorted Lists (C,C++,Java,Python)

Problem: Merge two sorted linked lists and return it as a new list. The new list should be made by ...

LeetCode笔记:21. Merge Two Sorted Lists

合并两个有序链表

Leetcode刷题记——21. Merge Two Sorted Lists(合并两有序链表)

一、题目叙述: Merge two sorted linked lists and return it as a new list. The new list should be...

LeetCode题解-21-Merge Two Sorted Lists

原题 本题较为简单,但是只想到了迭代的解法,没有想到递归。 迭代法 解题思路 比较L1与L2并增加新链表的节点,值为L1或者L2中较小的值。 代码 public c...

leetCode 21.Merge Two Sorted Lists (合并排序链表) 解题思路和方法

Merge Two Sorted Lists  Merge two sorted linked lists and return it as a new list. The new list sho...

LeetCode算法题——21. Merge Two Sorted Lists

题目 Merge two sorted linked lists and return it as a new list. The new list should be made by splici...

21.[Leetcode]Merge Two Sorted Lists

题意:归并两个排好序的链表我的思路;我们没有考虑递归的方法,也没有想到用递归解决,先贴出c++的非递归/** * Definition for singly-linked list. * stru...

leetcode[21 链表]Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing t...

Leetcode21: Merge Two Sorted Lists

还是和链表有关的问题,和第二题比较像,代码如下 # Definition for singly-linked list. # class ListNode(object): # def _...

leetcode 21. Merge Two Sorted Lists

1.题目 Merge two sorted linked lists and return it as a new list. The new...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)