19.删除链表的倒数第 N 个节点
解题思路:
1.首先拿到链表需要做预处理,如果为空或 <=0 就返回原链表
2.然后开始用 current指针遍历 ,并计数有多少节点
3.处理 counter 和 position 相同就是删除头节点
4.遍历结束就可以 将 current 重置 指向头节点, counter(链表节点总数) - position 就得到正向索引值
5.用for 指向目标节点的前一个节点,将目标节点的 前后节点相连,目标节点自然就会脱离链表,最后delete 将其释放
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int position) { if (head == nullptr || position <= 0 ){ return head; } ListNode* current = head; ListNode* temp = nullptr; int counter_length =0; while(current != nullptr ){ current = current->next; counter_length ++; } if (position == counter_length){ temp = head; head = head->next; delete temp; return head; } current = head; for (int i = 1; i < counter_length - position; ++i) { current = current ->next; } temp = current->next; current->next = temp->next; delete temp; return head; } };
|
时间复杂度 |
空间复杂度 |
$O(n)$ |
$O(1)$ |