1.题目
Given a linked list, remove the nth node from the end of list and return its head.
For 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.
Try to do this in one pass.
这个题目要求一次遍历就删掉倒数第n个节点,所以应该用快慢指针,让快指针先向前走n步,之后快慢指针一起向前走,直到快指针走到链尾,然后删掉慢指针之后的那个节点就可以。注意一点就是避免空指针,比如链表只有一个节点的情况、以及要删掉第一个节点的情况。
3.程序
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fast,slow;
fast=head;
slow=head;
while(n>0){
if(fast.next==null)
return head.next;//①注意一点就是避免空指针,比如链表只有一个节点的情况、以及要删掉第一个节点的情况
fast=fast.next;
n--;
}
while(fast.next!=null){
slow=slow.next;
fast=fast.next;
}
slow.next=slow.next.next;
return head;
}
}