删除链表中倒数第n个元素

//首先确保链表元素大于等于n个

ListNode* removeNthFromEnd(ListNode* head, int n){
//初始化快慢指针
ListNode* fast = head;
ListNode* slow = head;
//快指针确保领先慢指针n个位置
for(int i = 1; i <= n+1; i++){
  fast = fast -> next;
}
//当快指针走到尾巴的时候,慢指针正好是被删除结点的前一个结点
while(fast){
  fast = fast -> next;
  slow = slow -> next;
}

slow -> next = slow -> next -> next;
return head;
}

你可能感兴趣的:(删除链表中倒数第n个元素)