Shu-How Zの小窝

Loading...

19. 删除链表的倒数第 N 个结点

function ListNode(val, next) {
    this.val = (val===undefined ? 0 : val)
    this.next = (next===undefined ? null : next)
}

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function(head, n) {
    //head是否为空
    if(!head) return null;
    //创建一个虚头,创建两个指针,一个指向虚头pre.一个指向真实头节点cur
    let ret=new ListNode(-1, head),pre=ret,cur=head;
    //让cur移动K步
    for(let i=0;i<n;i++){
        cur=cur.next;
    }
    if(!cur) return head.next;
    //然后让两个指针一起移动,直到cur指向空
    while(cur){
        cur=cur.next;
        pre=pre.next;
    }
    //然后进行删除操作
    pre.next=pre.next.next;
    return ret.next;
};
posted @ 2026-05-07 16:55  KooTeam  阅读(5)  评论(0)    收藏  举报