LeetCode-21:合并两个有序链表(Java语言实现)

/**
 * 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 p, ListNode q) {
        if (p == null) {
            return q;
        }

        if (q == null) {
            return p;
        }

        if (p.val < q.val) {
            p.next = mergeTwoLists(p.next, q);
            return p;
        } else {
            q.next = mergeTwoLists(p, q.next);
            return q;
        }
    }
}

这个是 递归 版本,之前那个是 双指针 版本

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