Leetcode之合并有序单链表(简单 链表 递归)

合并两个已排序的链接列表并将其作为新列表返回。新列表应该通过拼接前两个列表的节点来完成。

例:

输入: 1-> 2-> 4,1-> 3-> 4
输出: 1-> 1-> 2-> 3-> 4-> 4

直接递归实现,代码来了

/**
 * 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;
        }
        if(l2==null) {
            return l1;
        }
        while(l1!=null||l2!=null){
            if(l1.val<l2.val){
                l1.next=mergeTwoLists(l1.next,l2);
                return l1;
            }else{
                l2.next=mergeTwoLists(l1,l2.next);
                return l2;
            }
        }
         return null;
    }
}

非递归也不能少,比递归运行时间短(粘贴大神代码)

/**
 * 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 head = new ListNode(0);
		ListNode current = head;
		while(l1 != null && l2 !=null) {
			int d1 = l1.val;
			int d2 = l2.val;
			if (d1 <= d2) {
				current.next = new ListNode(d1);
				current = current.next;
				l1=l1.next;
			}
			else 
				{current.next = new ListNode(d2);
				current = current.next;
				l2=l2.next;}
		}
		while(l1 == null && l2 != null) {
			current.next = new ListNode(l2.val);
			current = current.next;
			l2=l2.next;}
		
		while(l2 == null && l1 !=null) {
			current.next = new ListNode(l1.val);
			current = current.next;
			l1=l1.next;}
		
		return head.next;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_27817327/article/details/83142111