将链表传递给函数并确保它未被修改

Passing a linked list to a function and making sure it is not modified

本文关键字:确保 修改 函数 链表      更新时间:2023-10-16

有没有办法将链表传递给函数并确保它不会被修改?

我们可以将 const head 指针传递给函数,这将确保头部不会被修改。但是,该函数可以从 head 访问其他节点并修改这些节点。

可能你想尝试这样的事情:

class Node{
private: 
Node* _next;  
public:        
Node(Node* next) : _next(next){}
Node* getNext(){ return _next; }
const Node* getNext() const {return _next; }
};

附言恕我直言。C++ proramers 经常忽略引用并在不需要的地方使用指针。这可能是您情况的一种选择吗?:)

struct Node{ Node& _next; Node(Node& next) : _next(next){} }; 

PP.SS。在您的具体情况中,可能不需要第二个getNext。这只是为了让生活更轻松,如果你有函数接受 const 节点指针。在下面的示例中,我将尝试使用const方法进一步清除这个想法:

#include <iostream>
#include <cstdlib>
class Node{
private: 
Node* _next;  
public:        
Node(Node* next) : _next(next){}
Node* getNext(){ std::cout << "getNextn";  return _next;  }
const Node * getNext() const { std::cout << "getNext constn";  return _next; }
};
void f1(Node* node){ node->getNext(); }
void f2(const Node* node){ node->getNext(); }
int main() {
Node* n1 = new Node(NULL);
Node* n2 = new Node(n1);        
f1(n2);
f2(n2);
}

如果你想遍历linkedList而不改变它, 只需用常量函数重载遍历函数即可。