演算法分析與設計第三週
阿新 • • 發佈:2019-01-01
題目描述:
方法一:這是我最開始想到的方法,簡答直接。先找到連結串列的長度count,然後刪除第count-n+1個節點。需要兩遍遍歷。複雜度為o(n),n為連結串列的長度。
程式碼:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* find = head;
long count = 1;
while (find->next != NULL)
{
++count;
find = find->next ;
}
ListNode *curr = head;
ListNode *pre = NULL;
for (int i = 1; i <= count - n; ++i)
{
pre = curr;
curr = curr->next;
}
if (curr == head)
head = curr->next;
else
pre->next = curr->next ;
delete curr;
return head;
}
};
方法二:方法一的複雜度為o(n),已經是最優的複雜度,因為連結串列的操作只能通過頭一步步到達某個節點,就好像逐個比較法一樣。但是,還可以改進,使用兩個指標同時遍歷,保持前後指標距離為n個節點,遍歷一次,就可完成任務,使計算量大概下降一半。
程式碼:
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *first = head;
ListNode *second = head;
long count = 0;
while (first->next != NULL)
{
++count;
first = first->next;
if (count > n)
second = second->next;
}
if (count < n)
{
head = head->next;
delete second;
}
else
{
first = second->next;
second->next = second->next->next;
delete first;
}
return head;
}
};