描述:删除单链表的倒数第n个节点
分析:
- 主要思路是用两个指针遍历单链表,先让右指针前进n个节点,然后再让两个指针同步前进,这样右指针到达表尾null的时候,左指针的下一个即是要删除的节点
for (int i = 1; i <= n + 1; i++) {
right = right.next;
}
for (; right != null; right = right.next) {
left = left.next;
}
ListNode ahead = new ListNode(0);
ahead.next = head;
left.next = left.next.next;
完整实现:
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode ahead = new ListNode(0);
ahead.next = head;
ListNode left = ahead;
ListNode right = ahead;
for (int i = 1; i <= n + 1; i++) {
right = right.next;
}
for (; right != null; right = right.next) {
left = left.next;
}
left.next = left.next.next;
return ahead.next;
}