Js double pointer to solve ordered array, linked list merge

Double pointers are used in many question types, fast and slow pointers, left and right pointers. A simple double pointer can be used to solve the sorting problem of a linked list of ordered arrays.

FAQ 1: Leetcode21 merge two ordered linked lists

insert image description here

Idea : place a pointer on each of the two linked lists, create a new linked list containing dummy nodes, while traversing the two linked lists,

  • The linked list A has come to an end: the next bit of the new linked list is connected to the current position of B, and the B pointer goes one bit backward
  • The linked list B has come to an end: the next digit of the new linked list is connected to the current position of A, and the pointer of A moves backward one digit
  • Make a comparison before the end: the next bit of the new linked list points to the smaller one (the title requires ascending order), and goes one bit backward

And each round of traversal of the new linked list pointer goes one bit backward.

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var mergeTwoLists = function(l1, l2) {
    
    
let dummy = new ListNode(-1);
let cur1=l1;
let cur2=l2;
let temp = dummy;
while(cur1||cur2){
    
    
    if(!cur1){
    
    
        temp.next = new ListNode(cur2.val)
        cur2=cur2.next;
    }else if (!cur2){
    
    
        temp.next =new ListNode(cur1.val)
        cur1 = cur1.next;
    }else if (cur1.val<cur2.val){
    
    
        temp.next = new ListNode(cur1.val);
        cur1 = cur1.next;
    }else{
    
    
        temp.next = new ListNode(cur2.val);
        cur2 = cur2.next;
    }
    temp = temp.next;
}
return dummy.next;
};

FAQ 2: Merging of ordered arrays

The topics are similar, the ideas are similar, the process of creating new nodes is omitted, and the new array can be modified directly.

let a = [1, 2, 6];
let b = [4, 5, 7];
let lenA = a.length;
let lenB = b.length;
let res = new Array(lenA + lenB);
// console.log(res)
let curA = 0;
let curB = 0;
let temp;
while (curA < lenA || curB < lenB) {
    
    
    if (curA == lenA) {
    
    
        temp = b[curB++];
    } else if (curB == lenB) {
    
    
        temp = a[curA++];
    } else if (a[curA] < b[curB]) {
    
    
        temp = a[curA++];
    } else {
    
    
        temp = b[curB++];
    }
    res[curA + curB - 1] = temp;
}
console.log(res);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324049280&siteId=291194637