经典快慢双指针。
可参考下图,思路是一样的,细节可能不太一样。再注意边界问题就好

function ListNode(val, next) {this.val = (val === undefined ? 0 : val)this.next = (next === undefined ? null : next)}var removeNthFromEnd = function (head, n) {let slow = head, last = n, fast = headif (!head.next) return nullwhile (last > 0) {fast = fast.nextif (!fast) head = head.nextlast -= 1}while (fast && fast.next) {fast = fast.nextslow = slow.next}slow.next = slow.next.nextreturn head};// ----------------- test case -------------------var l1 = new ListNode(1), l2 = new ListNode(2), l3 = new ListNode(3), l4 = new ListNode(4), l5 = new ListNode(5);l1.next = l2l2.next = l3l3.next = l4l4.next = l5l5.next = nullvar h1 = new ListNode(1)var h2 = new ListNode(2)var h3 = new ListNode(3)h1.next = h2h2.next = h3const resultHead = removeNthFromEnd(h1, 3)
