[21] The combined force buckle two Ordered lists

First, the subject description:

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.

Example:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/merge-two-sorted-lists
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Second, the problem-solving ideas:

1, a special case: l1 l2 to return empty list, return empty list l1 is l2.
2, create a new list. The value of l1 and l2 are compared, if the value of l1 is small, the value of l1 put into new linked list; otherwise, the value of l2 into a new list.
3, need to think about the length l1 and l2 list. After the while loop if cur1 is null, cur2 is not null, the result list is sorted linked directly cur2 new node is inserted into the end of the list; otherwise the end of the list cur1 into the new node.

Third, Code Description:

/**
 * 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) {
    // l1 为空, 最终结果就是 l2
        if(l1==null){
            return l2;
        }
        if(l2==null){
            return l1;
        }
         ListNode newHead=new ListNode(-1);
         ListNode newTail=newHead;
         ListNode cur1=l1;
         ListNode cur2=l2;
         while(cur1!=null&&cur2!=null){
            if(cur1.val<cur2.val){
                newTail.next=new ListNode(cur1.val);
                newTail=newTail.next;
                cur1=cur1.next;
            }
            else{
                newTail.next=new ListNode(cur2.val);
                newTail=newTail.next;
                cur2=cur2.next;
            }
         }
         //while循环结束后,cur1和cur2有一个到达链表末尾,
         //把没到末尾的链表剩下的元素插入到新链表尾节点中
         if(cur1==null){
            newTail.next=cur2;
         }
         if(cur2==null){
             newTail.next=cur1;
         }
         return newHead.next;
    }
}
Published 75 original articles · won praise 14 · views 1899

Guess you like

Origin blog.csdn.net/qq_45328505/article/details/104631639