21. Merge Two Sorted Lists

MA:
/**
 * 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 cur=new ListNode(0);
        ListNode newHead=cur;
        ListNode oneNext;
        ListNode twoNext;
        while(l1!=null && l2!=null){
            oneNext=l1.next;
            twoNext=l2.next;
            if(l1.val<l2.val){
                cur.next=l1;
                l1=oneNext;
                cur=cur.next;
            }else{
                cur.next=l2;
                l2=twoNext;
                cur=cur.next;
            }
        }
        if(l1==null){
            cur.next=l2;
        }else{
            cur.next=l1;
        }
        return newHead.next;
    }
}

OA:递归解法
/** * 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; if(l1.val<l2.val){ l1.next = mergeTwoLists(l1.next,l2); return l1; } else{ l2.next = mergeTwoLists(l1,l2.next); return l2; } } }
迭代解法:

class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { // maintain an unchanging reference to node ahead of the return node. ListNode prehead = new ListNode(-1); ListNode prev = prehead; while (l1 != null && l2 != null) { if (l1.val <= l2.val) { prev.next = l1; l1 = l1.next; } else { prev.next = l2; l2 = l2.next; } prev = prev.next; } // exactly one of l1 and l2 can be non-null at this point, so connect // the non-null list to the end of the merged list. prev.next = l1 == null ? l2 : l1; return prehead.next; } }

评论

此博客中的热门博文

225 Implement Stack using Queues

232. Implement Queue using Stacks

20. Valid Parentheses