21. 合并两个有序链表将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
这题虽然也做出来了,但是做得不好,用了额外的新节点去组成新的链表。其实直接改变原有链表的指向就行了,不用开那么多空间。其他思路和官方解法二是一样的,还是不够简洁啊。
在链表前面开一个新的节点的作用是,不用在意第一步怎么处理,直接就可以用p.next;
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode mergeTwoLists(ListNode list1, ListNode list2) {ListNode p = new ListNode();ListNode q = p;while (list1 != null && list2 != null) {if (list1.val < list2.val) {ListNode newNode = new ListNode();newNode.val = list1.val;p.next = newNode;p = p.next;list1 = list1.next;} else {ListNode newNode = new ListNode();newNode.val = list2.val;p.next = newNode;p = p.next;list2 = list2.next;}}if (list1 != null) {p.next = list1;}if (list2 != null) {p.next = list2;}return q.next;}
}
官方解法二,看看简洁的写法
class Solution {public ListNode mergeTwoLists(ListNode l1, ListNode l2) {ListNode prehead = new ListNode(-1);ListNode prev = prehead;while (l1 != null && l2 != null) {if (l1.val <= l2.val) {prev.next = l1;l1 = l1.next;} else {prev.next = l2;l2 = l2.next;}prev = prev.next;}// 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可prev.next = l1 == null ? l2 : l1;return prehead.next;}
}作者:力扣官方题解
链接:https://leetcode.cn/problems/merge-two-sorted-lists/solutions/226408/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
官方解法一
递归。我向来是写不来递归的,看懂答案都勉强。看到一个写得比较好的帖子,这题的递归怎么理解请参照
https://blog.csdn.net/qq_38737428/article/details/117329875
class Solution {public ListNode mergeTwoLists(ListNode l1, ListNode l2) {if (l1 == null) {return l2;} else if (l2 == null) {return l1;} else if (l1.val < l2.val) {l1.next = mergeTwoLists(l1.next, l2);return l1;} else {l2.next = mergeTwoLists(l1, l2.next);return l2;}}
}作者:力扣官方题解
链接:https://leetcode.cn/problems/merge-two-sorted-lists/solutions/226408/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。