c++重载[]以打印链接列表的第n项
c++ overloading [] to print nth item of linked list
我有一个涉及不同链表操作的赋值。其中之一涉及重载方括号运算符,以便能够打印链表的第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;
}
我假设您希望返回与方括号中指定的value
相对应的节点。使用operator
关键字和运算符重载任何运算符,然后使用传递的参数。
有关更多信息,请查看以下内容::操作员过载
编辑::
正如erip和Lajos所指出的,在(value > size_of_list)
的情况下,应该有一种方法,在这种情况下,一个可能的解决方案是抛出一个异常,您可以稍后在程序中捕获该异常,以显示value
超出了限制。或者考虑到当前的实现,如果value > size_of_list
在这种情况下temp
将变成NULL
,那么在执行过程中,您可以检查返回的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;
在大型Lists的情况下,这将更加优化,这将避免for
循环的浪费执行!
相关文章:
- 从链接列表c++中删除一个项目
- 读取文件的最后一行并输入到链接列表时出错
- 下面是我为检测链接列表中的循环而制作的代码
- 有人能帮我处理这个链接列表吗?C++
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 为什么它只打印双链接列表的第一个值,而我的程序却崩溃了
- 链接列表运算符重载没有打印出我想要的内容
- 链接列表在 cpp 中包含不同的对象类
- 创建一个棋盘格或"Interweave"两个链接列表。IE 更改两个链表的指针
- 如何在构建链接列表时调整头、尾指针
- Shared_ptr双链接列表内存泄漏
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 在链接列表中查找元素 - C++
- 删除链接列表中剩余的最后一个节点
- 只有我的"链接列表"中的第一个节点正在打印
- 避免在使用链接列表从 deque 中删除最后一个节点时出现内存泄漏
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 将元素插入链接列表