题解 | #删除链表的倒数第n个节点#反转删除再反转
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
// 反转
head = reverse(head);
// 删除
ListNode temp = head;
while (n > 2) {
head = head.next;
n--;
}
if (n == 1) return reverse(head.next);
head.next = head.next.next;
// 反转
return reverse(temp);
}
public ListNode reverse(ListNode head) {
if (head == null) return null;
ListNode pre = null;
ListNode cur = null;
while (head != null) {
cur = head.next;
head.next = pre;
pre = head;
head = cur;
}
return pre;
}
}


阿里云成长空间 763人发布