leetcode19.删除链表的倒数第N个结点
19删除链表的倒数第N个结点
题目
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
用例
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
输入:head = [1], n = 1
输出:[]
输入:head = [1,2], n = 1
输出:[1]
求解
/**
* 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) {
let i = head;
let j = head;
let pre = head;
while(n>0){
j=j.next;
n--;
}
while(j!=null){
pre = i;
i=i.next;
j=j.next;
}
if(i==head){
return head.next;
}
pre.next = i.next;
i.next=null;
return head;
};

浙公网安备 33010602011771号