题目
给定一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
示例 1:
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
输入:head = [1], n = 1
输出:[]
输入:head = [1,2], n = 1
输出:[1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/SLwz0R
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:快慢指针
Java实现
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fast = head, slow = head;
while (n > 0) {
fast = fast.next;
n--;
}
if (fast == null) return head.next;
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return head;
}
}