yanggengzhen123 / leetcode-group

力扣小组
0 stars 0 forks source link

2022.03.24-第58题-19. 删除链表的倒数第 N 个结点 #60

Open yanggengzhen123 opened 2 years ago

yanggengzhen123 commented 2 years ago

https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/ 给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。 示例 1: image 输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]

示例 2: 输入:head = [1], n = 1 输出:[]

示例 3: 输入:head = [1,2], n = 1 输出:[1]

icodeish commented 2 years ago
function removeNthFromEnd(head, n) {
    let fast, slow
    fast = slow = head
    while (n-- > 0) {
        fast = fast.next
    }
    if (fast == null) {
        return head.next
    }
    while (fast != null && fast.next != null) {
        fast = fast.next
        slow = slow.next
    }
    slow.next = slow.next.next
    return head
}
yanggengzhen123 commented 2 years ago
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
    // 快慢指针
    let dummy:ListNode = new ListNode()
    dummy.next = head
    let n1 = dummy
    let n2 = dummy
    while(n-- >= 0){
        n2 = n2.next
    }
    while(n2 !== null){
        n2 = n2.next
        n1 = n1.next
    }
    n1.next = n1.next.next
    return dummy.next
};
BambooSword commented 2 years ago
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {

    const dummyHead = new ListNode(0);
    dummyHead.next = head; // 为了不考虑删除头结点的情况,我们增加一个虚拟头结点
    let fast = dummyHead;
    let slow = dummyHead;
    while(n--) { // 走n步,到达dummyHead后的第n+1个结点,也就是head后的第n个结点
        fast = fast.next;
    }
    while(fast.next) { // 同时走,若fast.next === null的时候,证明slow走到了 倒数第n+1个结点。
        slow = slow.next;
        fast = fast.next;
    }
    slow.next = slow.next.next; // 删除倒数第n个结点
    return dummyHead.next; // 返回头结点
};