力扣题目链接
给你一个链表,删除链表的倒数第 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]
方法一:快慢双指针
快指针先移动倒数的位数(比如倒数第二个那么快指针就先移动两位),然后快慢指针同时移动,当快指针移动到最后一个节点的时候,满指针刚好移动到指定删除位置的前一位,这个时候执行删除操作即可。
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode preHead = new ListNode(-1,head);
ListNode fast = preHead;
ListNode slow = preHead;
//快指针先移动相应的位数
while (n-- > 0) {
fast = fast.next;
}
//此时满指针开始移动,当快指针的下一个为空的时候也就是最后一个节点的时候
//满指针的下一个节点正好是要删除的元素
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return preHead.next;
}
}
方法二:计算链表长度
先计算链表长度,然后用链表长度减去倒数的位数加一
**注意:**这里使用for循环时开始的下标是1不是0
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode preHead = new ListNode(-1,head);
ListNode pre = preHead;
int len = getLength(head);
for (int i = 1; i < len - n + 1; i++) {
pre = pre.next;
}
pre.next = pre.next.next;
return preHead.next;
}
public int getLength (ListNode head) {
int length = 0;
while (head != null) {
length++;
head = head.next;
}
return length;
}
}