下面程序需要对如果删除的是第一个节点要进行判断,所以需要计算整个链表的长度
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:
int length(ListNode* head)
{
int count = 0;
ListNode* first = head;
while (first != nullptr)
{
++count;
first = first->next;
}
return count;
}
ListNode* removeNthFromEnd(ListNode* head, int n)
{
ListNode* first = head;
ListNode* second = head;
int len = length(head);
if (n == len)
{
ListNode* tmp = head;
head = head->next;
delete tmp;
return head;
}
for (int i = 0; i < n; ++i)
{
second = second->next;
}
while (second->next)
{
first = first->next;
second = second->next;
}
ListNode* tmp = first->next;
first->next = tmp->next;
delete tmp;
return head;
}
};
int main()
{
Solution A;
ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, nullptr))));
ListNode* tmp = A.removeNthFromEnd(head, 2);
return 0;
}
时间复杂度:O(L),其中 L 是链表的长度。 空间复杂度:O(1) 下面程序在头节点的前面又新增加了一个节点,这样就不用对头节点进行特殊的判断了
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)
{
ListNode* dummy = new ListNode(0, head);
ListNode* first = head;
ListNode* second = dummy;
for (int i = 0; i < n; ++i)
{
first = first->next;
}
while (first)
{
first = first->next;
second = second->next;
}
second->next = second->next->next;
ListNode* ans = dummy->next;
delete dummy;
return ans;
}
};
int main()
{
Solution A;
ListNode* head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, nullptr))));
ListNode* tmp = A.removeNthFromEnd(head, 2);
return 0;
}
时间复杂度:O(L),其中 L 是链表的长度。 空间复杂度:O(1)
|