题意:移除链表的倒数第n个节点
例子:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
public ListNode removeNthFromEnd(ListNode head, int n) {
//依然是两根指针的思路
ListNode start = new ListNode(0);
ListNode slow = start, fast = start;
slow.next = head;
//快指针先走n步
for(int i=1; i<=n+1; i++) {
fast = fast.next;
}
//快慢指针一起走
while(fast != null) {
slow = slow.next;
fast = fast.next;
}
//慢指针所指的位置就是倒数第n个节点,删除即可
slow.next = slow.next.next;
return start.next;
}