class Solution {
public ListNode middleNode(ListNode head) {
ListNode p = head;
ListNode q = head;
while (p != null && p.next != null) {
p = p.next.next;
q = q.next;
}
return q;
}
}
2 19. 删除链表的倒数第 N 个结点
2.1 题目
2.2 题解
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode p = head;
ListNode q = head;
for(int i = 0; i < n; i++){
p = p.next;
}
// 如果p结点此时为null,说明需要删除的是头结点,因为q指向head
if(p == null)
return head.next;
while(p.next != null){
p = p.next;
q = q.next;
}
q.next = q.next.next;
return head;
}
}
3 总结
3.1 快慢指针
快慢指针动画展示此。



