/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *pHead = head, *slow = head;
ListNode *ret = slow; // 哨兵节点
while(n--) { // 使得pHead和slow之间的gap 为n
pHead = pHead->next;
}
if(pHead == nullptr) {
return head->next;
}
while(pHead && pHead->next) { // 当phead指向末尾的时候,slow也就指向了第n个
slow = slow->next;
pHead = pHead->next;
}
slow->next = slow->next->next; // 去掉倒数第n个节点
return ret;
// write code here
}
};