和上一题一样,用快慢指针或者先遍历一遍找到总长度,就能定位到倒数n的节点,再删除即可。时间复杂度O(n),空间复杂度O(1)
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
ListNode fast = head;
ListNode slow = fast;
for(int i = 0; i < n; i++){
fast = fast.next;
}
if(fast == null) return head.next; //第一个就删除
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return head;
}
}