我想在 C++ 中创建类似于 Arraylist 的节点。当我创建一个方法 get();它说了错误。不懂就去网上找答案。你能帮我找到这个答案吗?
template<typename T>
struct Node{ //Node
T data;
Node<T> *next;
Node(){
next=NULL;
}
Node(T value){
data=value;
next=NULL;
}
};
template<typename T>
class LinkedList{ //class Node
public:
Node<T> *head;
Node<T> *tail;
void add(T value){ //method create newnode add to tail
Node<T> *newNode=new Node<T>(value);
if (head == NULL){
head=newNode;
tail=newNode;
}
else {
tail->next=newNode;
tail=newNode;
}
}
void PrintAll(string Name){ //method print all node
Node<T> *current;
int i=0;
current=head;
while (current != NULL ){
printf("%s[%d]=%d\n",Name.c_str(),i,current->data);
current=current->next;
i++;
}
}
T get(int index){ //method show node in parameter
Node <T> *current=head;
int count=0;
while (current != NULL){
if ( count == index) return current->next;
current=current->next;
count++;
}
}
};
错误:从“Node*”到“int”的无效转换 [-fpermissive]| 警告:控制到达非空函数的结尾 [-Wreturn-type]|
最佳答案
在 get()
中,您返回的是 Node*
而不是 T
,在 if
中准确。
你应该这样做:
T get(int index){ //method show node in parameter
Node <T> *current=head;
int count=0;
while (current != NULL){
if ( count == index) return current->data;
current=current->next;
count++;
}
}
你还应该处理索引无效的情况,在这些情况下抛出异常是可以的。
关于c++ - 链接列表(从 'Node<int>*' 到 'int' [-fpermissive]| 的无效转换),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56953778/