当前位置:   article > 正文

LeetCode.21. 合并两个有序链表_本题要求实现一个合并两个有序链表的简单函数mergelists,函数参数list1和list2是

本题要求实现一个合并两个有序链表的简单函数mergelists,函数参数list1和list2是

LeetCode.21. 合并两个有序链表

难度:easy

 

 方法一:递归:

  1. // 递归方法
  2. class Solution {
  3. public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
  4. if (list1 == null) {
  5. return list2;
  6. }
  7. if (list2 == null) {
  8. return list1;
  9. }
  10. if (list1.val < list2.val) {
  11. list1.next = mergeTwoLists(list1.next, list2);
  12. return list1;
  13. } else {
  14. list2.next = mergeTwoLists(list1, list2.next);
  15. return list2;
  16. }
  17. }
  18. }

复杂度分析:

  • 时间复杂度:O(m+n),m,n分别为两个链表节点数量
  • 空间复杂度: O(m+n)

方法二:迭代:

  1. // 迭代方法
  2. class Solution {
  3. public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
  4. if (list1 == null) {
  5. return list2;
  6. }
  7. if (list2 == null) {
  8. return list1;
  9. }
  10. // 虚拟头节点
  11. ListNode head = new ListNode();
  12. ListNode cur = head;
  13. while (list1 != null && list2 != null) {
  14. if (list1.val < list2.val) {
  15. cur.next = list1;
  16. list1 = list1.next;
  17. } else {
  18. cur.next = list2;
  19. list2 = list2.next;
  20. }
  21. cur = cur.next;
  22. }
  23. // 如果其中有一个链表的元素已经被全部添加到新链表中,则直接将另一个链表接在后面
  24. cur.next = (list1 == null? list2: list1);
  25. return head.next;
  26. }
  27. }

复杂度分析:

  • 时间复杂度:O(m+n),m,n分别为两个链表节点数量
  • 空间复杂度: O(1)
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/262511?site
推荐阅读
相关标签
  

闽ICP备14008679号