class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head == nullptr) return nullptr;
ListNode* dummyHead = new ListNode(0,head);
ListNode* pre = dummyHead;
ListNode* cur = dummyHead;
int size = 0;
int index = 0;
// 1.计算链表大小
while (pre->next != nullptr) {
pre = pre->next;
++size;
}
// 2.找到对应节点
while (index != size - n) {
cur = cur->next;
++index;
}
index == size-1 ? cur->next = nullptr
: cur->next = cur->next->next;
return dummyHead->next;
}
};
? ? ? ? 双指针,第一个指针测量链表长度,第二个指针找到对应删除节点并删除
? ? ? ? 时间复杂度:O(n) 空间复杂度O(1)