删除链表的倒数第n个节点
OJ 地址:删除链表的倒数第n个节点
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
// write code here
if(head == nullptr)
return nullptr;
ListNode *fast, *slow;
fast = slow = head;
while(fast && n--)
{
fast = fast->next;
}
if(!fast) //表示删除头节点
return head->next;
while(fast->next)
{
fast = fast->next;
slow = slow->next;
}
slow->next = slow->next->next;
return head;
}
};