19-删除链表的倒数第n个节点

19-删除链表的倒数第n个节点

力扣19

https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/

双指针经典题

前后指针,一遍扫描
前面的指针先走n个,然后前后指针一起移动,在要删除的节点前面停下,也就是pre.next != null
然后删掉第n个:post.next = post.next.next

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public ListNode removeNthFromEnd2(ListNode head, int n) {
if (head == null) return null;
ListNode root = new ListNode(0);
root.next = head;

ListNode pre = root, post = root;
while (n-- != 0) {
pre = pre.next;
}

while (pre != null && pre.next != null){
pre = pre.next;
post = post.next;
}
if (post != null && post.next != null) post.next = post.next.next;
return root.next;
}

其他链表类型的题目点击这里

其他双指针类型的题目点击这里

#
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×