链表问题,需要注意一下是倒着数还是正着数,和头结点会不会被删除即可
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null) {
return null;
}
// 头结点会被删除吗?
int length = 0;
ListNode p = head;
while (p != null) {
p = p.next;
length ++;
}
if (n == length) {
return head.next;
}
int index = 1;
p = head;
// 让p停在 j - 1 位置上
// 倒数变正数
int j = length - n + 1;
while (index < j - 1) {
p = p.next;
index++;
}
p.next = p.next.next;
return head;
}
标签:head,19,结点,next,链表,int,length,倒数第
From: https://www.cnblogs.com/jrjewljs/p/17516221.html