public ListNode removeNthFromEnd(ListNode head, int n) {
if (head.next == null) return null;
List<ListNode> l = new ArrayList<>();
while (head != null){
l.add(head);
head = head.next;
}
if (n == 1){
ListNode br = l.get(l.size() - 2);
br.next = null;
return l.get(0);
}
else if(n == l.size())
return l.get(1);
else{
ListNode fr = l.get(l.size() - n - 1); //n == n
ListNode br = l.get(l.size() - n + 1); //n == 1
fr.next = br;
return l.get(0);
}
}
利用快慢指针:
这里快指针要走n+1步,会出现走过界的情况,就在他们前面加入一个start节点,完全不影响,因为slow和fast始终差n.
public ListNode removeNthFromEnd(ListNode head, int n) {
//利用快慢指针
ListNode start = new ListNode(0);
ListNode slow = start, fast = start;
slow.next = head;
//slow,fast 相隔n个,让fast 先走n+1步
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 start.next;
}