LeetCode | 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.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
 //思路是每次取两个list中的小者,归并排序的思想
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1==null && l2==null) return null;
        if (l1==null && l2!=null) return l2;
        if (l1!=null && l2==null) return l1;
        
        ListNode l1_node = l1;       //循环取两个list中的元素出来比较
        ListNode l2_node = l2;       //相当于两个位置标志位,本list中的小者被取出后,标志位向后+1
        
        ListNode new_head = new ListNode(0);  //相当于新的list的头,最终返回new_head.next
        ListNode new_node = new_head;         //相当于新的list中的标志位,每次把比较出来的小者附到new_node的后边,同时new_node向后+1
        
        while (l1_node!=null && l2_node!=null){
            if(l1_node.val <= l2_node.val){
                new_node.next = l1_node;          //取小者附在new_node的后面
                l1_node = l1_node.next;           //标志node向后+1,略过这个小的node
            }else{
                new_node.next = l2_node;
                l2_node = l2_node.next;
            }
            //至此,新的list:new_head->小者node->小node后边的list元素
            new_node = new_node.next;   //第一次循环new_node从head变为最小的node,第二次循环变为第二小的node
        }
        if (l1_node == null) {new_node.next = l2_node;}    //说明l1不够,l2有剩余
        if (l2_node == null) {new_node.next = l1_node;}    //说明l2不够,l1有剩余
        
        return new_head.next;
    }
}

 

posted @ 2014-10-29 11:41  Mr.do  阅读(151)  评论(0编辑  收藏  举报