我有一个计算列表长度的函数。但这是线性时间。我如何将其转换为恒定时间(O(1))
struct Node
{
T data;
Node *next;
};
与Node *front;
Node *back;
此功能用于计算链接列表的长度
int length() const
{
Node *p = front;
int n = 0;
while (p != nullptr)
{
n++;
p = p->next;
}
return n;
}
答案 0 :(得分:5)
由于这看起来像是一项家庭作业,所以我不会为您做,但是由于您似乎对我的评论感到困惑,因此如果,您可以通过理论方法来更改列表新字段的结构可能如下所示:
template<typename T>
struct Node
{
T data;
Node* next;
};
template<typename Node>
struct List
{
// I assume there is a thingy that initializes these, otherwise bad things will happen
Node *front;
Node *back;
int length;
void add(Node* node) // No idea what the signature is
{
// I am not gonna do the adding for you
// If everything went fine increase the length
length += 1;
}
void remove(Node* node) // Again, no idea of the signature
{
// Again, not gonna do the removal
// If everything went fine decrease the length
length -= 1;
}
int get_length() const
{
return length;
}
};