题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
http://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
/**
- 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 && n <= 0) return head;
ListNode* fast = head;
ListNode* slow = head;
//先让快慢指针保持n距离
while(n && fast)
{
fast = fast->next;
n--;
}
//n > 0说明链表的长度没有n大
if(n > 0)
return head;
if(fast == nullptr) //fast == nullptr倒数第n个节点刚好是第一个结点
return head->next;
while(fast->next != nullptr) //大部分的情况
{
slow = slow->next;
fast = fast->next;
}
slow->next = slow->next->next;;
return head;
}
};