思路:
第一种思路是先遍历一遍链表,计算出链表长度,然后再遍历一次。
第二种思路是使用快慢指针fast和slow,fast比slow超前n个结点,不断将fast和slow后移(注意这时我们需要用一个last节点来指向slow的左边节点),当fast.next=null时, fast到达了链表末尾,slow指向的就是倒数第n个结点,last指向的就是倒数第n+1个节点,这时就可以直接进行删除操作。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null)
{
return null;
}
int i = 1;
ListNode Fast = head;//Fast最后指向链表末尾节点
ListNode Slow = head;//Slow最后指向倒数第n个节点
while(i<n)
{
Fast = Fast.next;
i++;
}
ListNode last = null;
while(Fast.next!=null)
{
Fast = Fast.next;
last = Slow;
Slow = Slow.next;
}
if(Slow == head)
{
head = head.next;
return head;
}
last.next = Slow.next;
Slow.next = null;
return head;
}
}