2022春节后,LeetCode之链表

118 阅读1分钟

1290. 二进制链表转整数

1290. 二进制链表转整数

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {number}
 */
/* 
    5÷2=2余1 
2÷2=1余0 
1÷2=0余1  
 ===> 得出二进制 101 .
反推回去 商 x 除数 + 余数 
=> 0 x 2 + 1 = 1 
-> 1 x 2 + 0 = 2
-> 2 x 2 +1 = 5
*/
var getDecimalValue = function(head) {
    let res = 0;
    while (head) {
        res = res * 2 + head.val;
        head = head.next;
    }
    return res;
};

1669. 合并两个链表

1669. 合并两个链表

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} list1
 * @param {number} a
 * @param {number} b
 * @param {ListNode} list2
 * @return {ListNode}
 */
var mergeInBetween = function(list1, a, b, list2) {
    let prev = null;
    let curA = list1;
    let c = false;
    let count = 0;
    while (count !== b) {
        if (!c) {
            prev = curA;
        }
        
        curA = curA.next;
        count += 1;
        if (count === a) {
            /* prev 停止 */
            c = true;
        } 
    }
    /* curA === b  */
    prev.next = list2;
    let curB = list2;
    while (curB.next) {
        curB = curB.next;
    }
    curB.next = curA.next;
    return list1;
};

1019. 链表中的下一个更大节点

1019. 链表中的下一个更大节点

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {number[]}
 */
 var nextLargerNodes = function(head) {
    if(!head) return []
    let ret = []
    while(head){
        let r = head.next
        let temp = 0
        while(r){
            if(r.val > head.val){
                temp = r.val
                break 
            }
            r = r.next
        }
        ret.push(temp)
        head = head.next
    }
    return ret
};