目录
题目:
代码(首刷自解 2024年1月13日):
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)
代码(二刷自解 2024年3月4日)
双指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head == nullptr) return nullptr;
ListNode* dummyHead = new ListNode();
dummyHead->next = head;
ListNode* cur = dummyHead;
ListNode* pre = dummyHead;
while (n-- && cur->next != nullptr) {
cur = cur->next;
}
while (cur->next != nullptr) {
cur = cur->next;
pre = pre->next;
}
pre->next = pre->next == nullptr ? nullptr : pre->next->next;
return dummyHead->next;
}
};
代码(三刷自解 2024年4月22日 6min)
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// 删除倒数第n个,即获得倒数第n + 1 个
if (!head) return head;
ListNode* dummy = new ListNode(0, head);
ListNode* cur = dummy;
ListNode* pre = dummy;
while (n--) {
cur = cur->next;
}
while (cur->next) {
cur = cur->next;
pre = pre->next;
}
ListNode* tmp = pre->next;
pre->next = tmp->next;
delete tmp;
return dummy->next;
}
};
代码(四刷自解 2024年8月9日)
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
// 双指针,找到倒数第n个节点的前一个节点
if (!head) return head;
ListNode* dummyHead = new ListNode(0, head);
auto fast = dummyHead;
auto slow = dummyHead;
n++;//要倒数第n - 1个节点
while (n--) fast = fast->next;
while (fast != nullptr) {
fast = fast->next;
slow = slow->next;
}
auto tmp = slow->next;
slow->next = slow->next->next;
delete tmp;
return dummyHead->next;
}
};