LeetCode-探索-初级算法-链表-4. 合并两个有序链表(个人做题记录,不是习题讲解)

LeetCode-探索-初级算法-链表-4. 合并两个有序链表(个人做题记录,不是习题讲解)

LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/

  1. 合并两个有序链表
  • 语言:java

  • 思路:新建一个ListNode作为head,然后判断链表a和链表b的数值大小,每次往head后面添加子节点

  • 代码(1ms):

    /**
     * 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 a = l1;
            ListNode b = l2;
            ListNode head = new ListNode(0);
            ListNode res = head;
            while(a!=null&&b!=null){
                if(a.val<=b.val){
                    head.next = a;
                    a = a.next;
                    head = head.next;
                }else{
                    head.next = b;
                    b = b.next;
                    head = head.next;
                }
            }
            if(a!=null)
                head.next = a;
            else if(b!=null)
                head.next = b;
            return res.next;
        }
    }
    
  • 参考代码(0ms)递归:

    ​ 直接在原本的ab两个链表上操作,所以最后先遍历到null的返回另外一个链表;每次递归判断是要a后面添加b还是b后面添加a,如果a后面添加b,那么久返回a;

    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;
            }
        }
    }
    
  • 参考后重写:

    /**
     * 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;
            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;
                }
            }
        }
    }
    
发布了60 篇原创文章 · 获赞 6 · 访问量 5541

猜你喜欢

转载自blog.csdn.net/Ashiamd/article/details/102263119