算法题:有序链表合并

1.递归

class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }

    }

public ListNode trainningPlan(ListNode l1, ListNode l2) {
        /**
         * 递归
         */
        if (l1 == null){
            return l2;
        } else if (l2 == null) {
            return l1;
        }else if (l1.val < l2.val){
            l1.next = trainningPlan(l1.next, l2);
            return l1;
        }else{
            l2.next = trainningPlan(l1,l2.next);
            return l2;
        }
    }

2.迭代

class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }

    }

public ListNode trainningPlan2(ListNode l1, ListNode l2) {
        /**
         * 迭代
         */
        ListNode preHead = new ListNode(-1);
        ListNode pre = preHead;
        while (l1 != null && l2 != null){
            if (l1.val < l2.val){
                pre.next = l1;
                l1 = l1.next;
            }else{
                pre.next = l2;
                l2 = l2.next;
            }
            pre = pre.next;

        }
        pre.next = l1 == null ? l2 : l1;
        return preHead.next;
    }

你可能感兴趣的:(算法题,算法,链表,数据结构)