2015年4月8日星期三

merge two sorted list leetcode

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.
Example
Given 1->3->8->11->15->null, 2->null , return 1->2->3->8->11->15->null
对于新表声明一个表头dummy 和一个指针head
然后每个list有一个指针来遍历两个list

时间O(m + n) 空间O(1)


public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode head = dummy;
        ListNode left = l1;// 指针可以不用left 和right
        ListNode right = l2;//直接用l1, l2也可以
        while (left != null && right != null){
            if (left.val <= right.val){
                head.next = left;
                head = head.next;
                left = left.next;
            } else {
                head.next = right;
                head = head.next;
                right = right.next;
            }
        }
        if (left == null){
            head.next = right;
        }
        if (right == null){
            head.next = left;
        }
        return dummy.next;
    }
}

没有评论:

发表评论