首页 > 代码库 > [LeetCode]21 Merge Two Sorted Lists

[LeetCode]21 Merge Two Sorted Lists

https://oj.leetcode.com/problems/merge-two-sorted-lists/

http://blog.csdn.net/linhuanmars/article/details/19712593

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
                
        if (l1 == null && l2 == null)
            return null;
        
        ListNode toReturn = null;
        ListNode curNode = null;
        ListNode lastNode = null;
        while (l1 != null || l2 != null)
        {
            // Select current node;
            if (l1 == null)
            {
                curNode = l2;
                l2 = l2.next;
            }
            else if (l2 == null)
            {
                curNode = l1;
                l1 = l1.next;
            }
            else if (l1.val < l2.val)
            {
                curNode = l1;
                l1 = l1.next;
            }
            else
            {
                curNode = l2;
                l2 = l2.next;
            }
            
            if (toReturn == null)
                toReturn = curNode;
            
            if (lastNode != null)
                lastNode.next = curNode;
            lastNode = curNode;
        }
        
        return toReturn;
    }
}


[LeetCode]21 Merge Two Sorted Lists