其他分享
首页 > 其他分享> > LeetCode每日一练【19】

LeetCode每日一练【19】

作者:互联网

Remove Nth From From End Of List

我的解法

第一次提交

介绍

别看我, 看我干啥? 看代码啊!

思路

  1. 构建链表: new ListNode(0, arr)
  2. 创建两个指针: x_pointer(遍历链表), y_pointer(遍历链表 - 删除节点)

代码

/*
 * @Author: fox
 * @Date: 2022-05-03 07:11:41
 * @LastEditors: fox
 * @LastEditTime: 2022-05-03 08:27:38
 * @Description: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
 */

class ListNode {
    constructor(val, next) {
        this.val = (val === undefined ? 0 : val);
        this.next = (next === undefined ? null : next);
    }
}
/**
 * @description: Runtime: 90.90%  Memory Usage: 83.27%
 * @param {ListNode} head 链表头结点
 * @param {number} n 从链表末尾倒数的第几个节点
 * @return {ListNode}
 */
const removeNthFromEnd = (head, n) => {
    const listNode = new ListNode(0, head); // 构建链表
    
    let x_pointer = listNode;
    let y_pointer = listNode;

    while (x_pointer.next) {
        x_pointer = x_pointer.next;
        
        if (n <= 0) { // 关键:通过不断减去差值来判断是否移动y_pointer指针
            y_pointer = y_pointer.next;
        } else {
            n--;
        }
    }

    y_pointer.next = y_pointer.next.next;

    return listNode.next;
};

let head = [1, 2, 3, 4, 5]
console.log(removeNthFromEnd(head, 2)) // [1, 2, 3, 5]

head = [1]
console.log(removeNthFromEnd(head, 1)) // []

head = [1, 2]
console.log(removeNthFromEnd(head, 1)) // [1]

标签:head,ListNode,val,19,每日,next,链表,pointer,LeetCode
来源: https://www.cnblogs.com/mapodoufu/p/16217640.html