题解 | 删除链表的倒数第n个节点
删除链表的倒数第n个节点
https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head == nullptr) return nullptr;
ListNode* count_node = head;
int count_n = 0;
while (count_node) {
count_node = count_node->next;
count_n++;
}
int site_node = count_n-n;
ListNode* now_node = head;
if (site_node == 0 ) return head->next;
while (now_node&&site_node>1) {
now_node = now_node->next;
site_node--;
}
if (now_node->next) {
ListNode* nxt = now_node->next->next;
now_node->next->next = nullptr;
now_node->next = nxt;
}
return head;
}
};

