删除链表的倒数第 N 个结点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1
输出:[]
示例 3:
输入:head = [1,2], n = 1
输出:[1]
提示:
链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
/** * 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 pointFront,pointBack ; let flag=0,reArray = new ListNode(); head.front = null; pointFront = pointBack = head; let count = 1; // 使单链表变成双向链表 while(pointBack.next!= null){// pointFront始终指向的是前一个节点 pointBack始终指向的是后一个节点 pointBack = pointFront.next; pointBack.front = pointFront; pointFront = pointBack; flag = 1; } if(flag==0) return head.next; pointFront = pointBack.front; // 找到最后一个结点,现在开始往回找 while(count < n){//小于说明还没有找到 pointBack = pointFront; pointFront = pointFront.front; count++; } if(pointBack.front == null) return pointBack.next; else pointFront.next = pointBack.next; return head; };