19. 删除链表的倒数第N个节点
题解
预设指针pre,start,end,使pre.next = head,start比end多走n步,n—,之后找到要删除的结点的上一个节点(技巧是start.next == null跳出循环),删除即可。最后返回pre.next,因为head结点可能已经被删除。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre = new ListNode(0);
pre.next = head;
ListNode start = pre, end = pre;
while(n != 0) {
start = start.next;
n--;
}
while(start.next != null) {
start = start.next;
end = end.next;
}
end.next = end.next.next;
return pre.next;
}
}