题目链接 https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
蛮简单的,循环一边拿出size,再来一遍删除定位节点
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//特殊情况
while(head == null){
return head;
}
ListNode dummyNode = new ListNode(-1, head);
int size = 0;
//一般情况
while(head != null){
head = head.next;
size++;
}
head = dummyNode;
for(int i = 0; i < size - n; i++){
head = head.next;
}
head.next = head.next.next;
return dummyNode.next;
}
}
双指针的办法很巧,巧在如何确定窗口的大小
原来是根据倒数第n个,n可以卡住窗口的大小
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//特殊情况
while(head == null){
return head;
}
ListNode dummyNode = new ListNode(-1, head);
ListNode slow = dummyNode;//慢指针可以开始设在前面,也就是慢一步
ListNode fast = head;
//一般情况
for(int i = 0; i < n; i++)//快指针先走
fast = fast.next;
while(fast != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummyNode.next;
}
}