我有一个作业涉及不同的链表操作。其中之一涉及重载方括号运算符,以便能够打印链表的第 i 个元素。我已经完成了其他所有事情,但我真的迷失了。这就是我正在使用的。列表类如下:
class List {
public:
// Creates a default empty list
List();
// Simple destructor
~List();
// Insert "data" at the very end of the list
void AddToFront(int data);
// Remove and return the first data item from the list.
int deleteFront();
// Prints the list
void Print() ;
// Returns the size of the list
unsigned int Size() const;
//overloaded assignment operator
Node operator[](unsigned int i) ;
private:
Node *m_head;
};
此外,这是我的节点类:
class Node {
public:
Node();
~Node();
Node(int data);
int m_data;
Node *m_next;
};
任何有关重载 [] 运算符的帮助将不胜感激。
最佳答案
Node* operator [] (int value) {
Node *temp = this->m_head;
for(int i = 0; i < value && temp!=NULL; i++) {
temp = temp->m_next;
}
return temp;
}
我假设您要返回与方括号中指定的值
对应的节点。您可以使用 operator
关键字重载任何运算符,后跟运算符,然后是传递的参数。
有关更多信息,请查看此::Operator overloading
编辑::
正如 erip 和 Lajos 所指出的,应该有一种方法,以防 (value > size_of_list)
,在这种情况下,一个可能的解决方案是抛出一个异常,您稍后可以捕获该异常您的程序显示 value
超出范围。或者考虑当前的实现,如果 value > size_of_list
在这种情况下 temp
将变为 NULL
,因此在执行期间您可以检查 的值是否code>Node *
返回是否为NULL
。
进一步优化的方法是在List
类中保留一个变量size_of_list
,然后我们可以简单地添加一个if
条件像这样的函数::
if(value >= size_of_list) // equal to sign is put, considering your `size_of_list` starts from 1
return NULL;
这将在大型列表的情况下得到更优化,这将避免浪费执行 for
循环!
关于c++重载[]以打印链表的第n项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34145270/