Leetcode 21.Merge Two Sorted Lists
程序员文章站
2024-03-22 14:56:10
...
本题思路很简单, 依次比较链表指针目前指向的结点的值, 将较小的值放到新链表中, 同时将链表指针更新, 直到其中一个链表为空, 那么接下来的就直接是另一个非空链表了.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode l = new ListNode(-1);
ListNode head = l;
if(l1 == null || l2 == null )
return l1 == null ? l2 : l1;
while(l1 != null && l2 != null) {
if(l1.val <= l2.val) {
l.next = l1;
l1 = l1.next;
} else {
l.next = l2;
l2 = l2.next;
}
l = l.next;
}
l.next = l1 == null? l2 :l1;
return head.next;
}
}
主要是为了记录一下大神的简介代码, 使用递归的方法 :
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null)
return l2;
if(l2 == null)
return l1;
if(l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
这里并没有新建立结点, 而是在原有的链表上进行连接操作. 很清晰的代码. 学习一下
推荐阅读
-
Leetcode 21.Merge Two Sorted Lists
-
LeetCode[链表] - #21 Merge Two Sorted Lists 博客分类: LeetCode LeetCodeJavaAlgorithm题解LinkedList
-
Leetcode题解 4. Median of Two Sorted Arrays 【Array】
-
leetcode.array--4. Median of Two Sorted Arrays
-
【leetcode】#4 Median of Two Sorted Arrays【Array】【Hard】
-
LeetCode 160 - Intersection of Two Linked Lists
-
Merge Two Sorted Lists(C++)
-
[LeetCode] 004. Median of Two Sorted Arrays (Hard) 经典分治
-
【LeetCode】Two Sum & Two Sum II - Input array is sorted & Two Sum IV - Input is a BST
-
LeetCode C++ 599. Minimum Index Sum of Two Lists【Hash Table】简单