
简单给你一个链表,删除链表的倒数第 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]
作者:力扣 (LeetCode)
链接:https://leetcode-cn.com/leetbook/read/linked-list/jf1cc/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
代码
/*** 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 fast = head;let slow = head;// 快指针移动到慢指针的n个位置之后,慢指针还在初始位置while (n-- > 0) {fast = fast.next;}// 将快指针移动到末尾while (fast && fast.next) {fast = fast.next;slow = slow.next;}// 如果fast为null,则说明链表不够长if (fast === null) {return head.next;// null}slow.next = slow.next.next;return head;};
思路:快慢指针
- 首先我们令快慢指针都初始化为head;
- 将快指针移动到慢指针n个位置之后;
- 进行判断,若快指针为null则说明链表不够长,只能返回head.next,即null;
- 若链表长度足够则根据链表的性质,直接将slow.next指向为slow.next.next;
