力扣-链表-19 删除链表倒数第N个节点
思路
链表题目中操作链表的需要找到要操作节点的上一个节点,所以cur是当前想要操作的节点上一个节点
代码
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy_head = new ListNode();
dummy_head->next = head;
int size = 0;
while(head != nullptr){
head = head->next;
size++;
}
ListNode* cur = dummy_head;
while(size - n){
cur = cur->next;
n++;
}
cur->next = cur->next->next;
return dummy_head->next;
}
};