思路:
1.首先让快指针走K步,如果fast==null(K等于链表的长度),说明要删除的为链表第1个节点,直接返回head.next
2.然后让快慢指针一起走,直到走到链表结束,此时慢指针在倒数第K+1个节点,直接执行slow.next=slow.next.next即可。
参考代码:
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
//先让快指针走n步,然后慢指针开始走,当快指针走到头时,慢指针走到倒数第n+1个节点,然后执行slow.next=slow.next.next;
if(head==null){
return null;
}
ListNode fast=head;
ListNode slow=head;
//先让快指针走n步
for(int i=0;i<n;i++){
fast=fast.next;
}
//如果fast==null,此时是删除链表第1个节点
if(fast==null){
return head.next;
}
//快慢指针一起走
while(fast.next!=null){
fast=fast.next;
slow=slow.next;
}
//
slow.next=slow.next.next;
return head;
}
}