我创建了一个链表:struct Node和List Class,我在我的main方法外面使用它,
#include "Lists.cpp"
#include <cstdlib>
using namespace std;
int main(){
Lists l = new Lists(1);
l.add(2);
l.add(3);
l.add(4);
l.add(5);
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但它会产生一个错误,表示"从List*到int的转换无效".我使用外面的课吗?我有点困惑,我将如何解决这个问题.
#include <cstdlib>
#include <iostream>
using namespace std;
struct Node{
int data;
Node *next;
Node(int i){
data = i;
next = NULL;
}
};
class List{
Node *head;
public:
List(int i){
head = new Node(i);
}
void addToHead(int i){
Node *temp = new Node(i);
temp->next = head;
head = temp;
}
void add(int i){
Node *currNode = head;
while(currNode!= NULL){
if(currNode->next == NULL){
currNode->next = new Node(i);
break;
}
else{
currNode = currNode-> next;
}
}
}
void deleteNode(int i){
Node *currNode = head;
Node *prevNode = NULL;
while(currNode!= NULL){
if(currNode->data == i) {
if(prevNode== NULL){
head = head->next;
}
else{
prevNode->next = currNode->next;
}
}
prevNode = currNode;
currNode = currNode -> next;
}
}
void insert(int position, Node *n){
Node *currNode= head;
Node *prevNode = NULL;
for(int counter = 0; counter>= position && currNode!= NULL; counter++){
if(counter==position){
Node *temp = currNode;
n->next = currNode;
prevNode->next= n;
}
prevNode = currNode;
currNode = currNode-> next;
}
}
void traverse(Node *node){
if(node!=NULL){
cout<< node-> data <<endl;
traverse(node->next);
}
}
};
Run Code Online (Sandbox Code Playgroud)
Lists l = new Lists(1);
Run Code Online (Sandbox Code Playgroud)
应该:
Lists *l = new Lists(1);
Run Code Online (Sandbox Code Playgroud)
new 提供指针.
您得到该特定错误的原因是,如果转换链Lists *- > int- > Lists有效,该行将有效.第二个在这里是有效的,因为构造函数,但第一个不是.