21. Merge Two Sorted Lists

题目:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

链接: http://leetcode.com/problems/merge-two-sorted-lists/

题解:合并两个排序的单链表, 创建一个dummy head,然后进行合并。 Time Complexity - O(n),Space Complexity - O(1)。

public class Solution {

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        if(l1 == null)

            return l2;

        if(l2 == null)

            return l1;

        ListNode result = new ListNode(-1);

        ListNode node = result;

        

        while(l1 != null && l2 != null){

            if(l1.val < l2.val){

                node.next = l1;

                l1 = l1.next;

            }

            else{

                node.next = l2;

                l2 = l2.next;

            }

            node = node.next;

            node.next = null;

        }

        

        if(l1 != null)

            node.next = l1;

        else if (l2 != null)

            node.next = l2;

        return result.next;

    }

}

 

你可能感兴趣的:(merge)