编辑
Merge Two Sorted Lists
本文访问次数:0
  1. 1. 问题链接
  2. 2. 问题描述
  3. 3. 解决办法

问题链接

问题描述

给出两个排序过的列表,将它们融合成一个并返回头。

解决办法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = null;
        ListNode s1 = null;
        ListNode s2 = null;
        if(l1 == null){
            return l2;
        }
        if(l2 == null){
            return l1;
        }
        if (l1.val < l2.val) {
            head = l1;
            s1 = l1.next;
            s2 = l2;
        } else {
            head = l2;
            s1 = l1;
            s2 = l2.next;
        }
        return mergeTwoLists(head,head, s1, s2);
    }

    public static ListNode mergeTwoLists(ListNode head,ListNode start, ListNode s1, ListNode s2) {
        if(s1 == null){
            if(s2 != null){
                start.next = s2;
            }
            return head;
        }
        if(s2 == null){
            if(s1 != null){
                start.next = s1;
            }
            return head;
        }
        if (s1.val < s2.val) {
            start.next = s1; 
            return mergeTwoLists(head,s1,s1.next,s2);
        }
        else{
            start.next = s2;
            return mergeTwoLists(head,s2,s1,s2.next);
        }
    }
}

需要输入验证码才能留言

没有任何评论