题目:
19. Remove Nth Node From End of List (Medium)
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
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.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
题目大意:
给出一个链表和一个整数,得出删除该链表的倒数第n个节点后的链表
进阶:能用一趟扫描实现要求吗?(使用双指针——“快慢指针”)
解题思路:
一个典型的“快、慢指针”的应用。快指针先走n步,然后慢指针和快指针再一起走快指针剩下的步数,得出的结果慢指针就少走n步,即可得到所求。
代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24注意:本题有些极限的测试数据;
如[1],n=1; [1,2],n=2这类n等于数组长度的情况。
Java:
pubic ListNode removeNthFromEnd(ListNode head,int n){
if(head == null || n < 0) return null;
ListNode fast = head;
while(n-- > 0){
fast = fast.next;
}
if(fast == null) return head.next;//针对n等于所给数组得长度情况,单独判断
//此时fast已经走完了整个数组,到最后一个节点的next
//这种情况删除倒数整个数组长度的节点就是删除第一个节点
ListNode slow = head;
while(fast.next != null){
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return head;
}
Python: