LeetCode链接:19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
思路:用快慢指针,fast指针和slow指针相差n个结点,并定义一个temp结点指向head,当fast < n时fast = fast.next,当fast != null时,slow = slow.next,fast = fast.next,最后将left.next = left.next.next,并返回ans = temp.next
java代码:
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode temp = new ListNode(0,head);
ListNode right = head;
ListNode left = temp;
for(int i = 0; i < n; i++){
right = right.next;
}
while(right != null){
left = left.next;
right = right.next;
}
left.next = left.next.next;
ListNode ans = temp.next;
return ans;
}
}