[Power button] to merge the two ordered list

The two ordered lists into a new sorted list and return. The new list is by all nodes in a given mosaic composed of two lists.

The subject of the force from the buckle exam

Examples

Input: 1-> 2-> 4, 1-> 3-> 4
Output: 1-> 1-> 2-> 3-> 4-> 4

Thinking

The establishment of a new list, select the new node puppet list of code written up is simple with a head node.
A new list is provided in the end node, the end node to the nodes used for insertion of the tail in the new list.
Loop through the list l1 and l2 list, corresponding to the tail of the new list is added to determine the size of the end of the cycle that traverse the linked list l1 or l2 list to the end, then exit the loop.
Determine which traverse the list has not been completed, there is no complete traversal put together the rest of the node is added to the end of the new list.

Code
/**
 * 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;
        }
        //设置一个傀儡节点
        ListNode newHead=new ListNode(-1);
        //cur1和cur2分别遍历l1和l2链表
        ListNode cur1=l1;
        ListNode cur2=l2;
        //新链表的尾部
        ListNode newtail=newHead;
        while(cur1!=null&&cur2!=null){
             if(cur1.val<=cur2.val){
                newtail.next=cur1;
                 cur1=cur1.next;
             }else{
                newtail.next=cur2;
                 cur2=cur2.next;
             }
             newtail=newtail.next;  
        }
        //哪个不为空,就把哪个链表剩下的所有节点尾插到新链表结尾
        if(cur1!=null){
            newtail.next=cur1;
        }
        if(cur2!=null){
            newtail.next=cur2;
        }
       return newHead.next;
    }
}
Published 24 original articles · won praise 46 · views 3339

Guess you like

Origin blog.csdn.net/qq_45619426/article/details/104542316