leetcode face questions - 25. The combined two sorted list of interview questions

25. The interview questions to merge two sorted lists
to enter two ascending order of the list, merge the two lists and the list of the new node is still ascending order of.
Example 1:
Input: 1-> 2-> 4, 1-> 3-> 4
Output: 1-> 1-> 2-> 3-> 4-> 4
limits:
0 <= chain length <= 1000
Solving ideas: setting a first virtual node were compared with two pointers, inserting new data list is small, then the pointer is moved, the new current pointer list also after the shift, the above-described operation is repeated. Finally, the details of the operation.

/**
 * 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 newNode = new ListNode(0);
        ListNode cur = newNode;
        while(l1 != null && l2 != null){
            if(l1.val > l2.val)
            {
                cur.next = l2;
                l2 = l2.next;
            }else{
                cur.next = l1;
                l1 = l1.next;
            }
            cur = cur.next;
        }
        if(l1 != null){
            cur.next = l1;
        }
        if(l2 != null){
            cur.next = l2;
        }
        return newNode.next;
    }
}
Released two original articles · won praise 0 · Views 11

Guess you like

Origin blog.csdn.net/qq_40860196/article/details/104696226