现在使用图形,并且非常坚持创建链表数组(邻接列表(,尝试了一些变体,但得到了这个错误:
[错误] 与"运算符>>"不匹配(操作数类型为"std::istream {aka std::basic_istream}"和"node*"(
class node {
int data;
node* next;
node(int x){
data = x;
next = NULL;
}
};
void SS_in(){
int nver;
node **listik;
cout << "vvedite kolvo vershin";
cin >> nver;
for (int i=0; i<nver;i++){
cout << "V" << i << ": ";
cin >> listik[i];
}
}
我只会干预您遇到的编译错误,而不是由于您的请求不清楚而需要构建链表。
必须先重载类的运算符>>
,然后才能使用它:
#include <iostream>
using namespace std;
class node {
public :
int data;
node* next;
node(int x){
data = x;
next = NULL;
}
friend istream & operator >> (istream &in, node &myNode);
};
istream & operator >> (istream &in, node &myNode)
{
cout << "Enter node data :"<< endl;
in >> myNode.data;
return in;
}
int main()
{
node myNode(2);
cin >> myNode;
return 0;
}
只定义了节点和图形(列表(。
在此阶段,可以修复错误:
#include <iostream>
using namespace std;
class node {
public:
int data;
node* next;
node (int x) {
data = x;
next = NULL;
}
};
void SS_in () {
int nver;
std::cout << "vvedite kolvo vershin";
std::cin >> nver;
node** listik = new node * [nver];
int tempData;
for (int i = 0; i < nver; i++) {
cout << "V" << i << ": ";
cin >> tempData;
listik[i] = new node(tempData);
}
}
void main () {
SS_in ();
}
应添加类邻接列表(链表(。
此代码:
node **listik;
...
...
cin >> listik[i];
在两个方面是错误的。
1(listik
未初始化,因此listik[i]
也是如此。换句话说 - 您正在尝试读取您的程序(很可能(不拥有的内存。
2(由于listik
是"指针到节点的指针",因此listik[i]
是"指向节点的指针"。要求用户键入指针值是没有意义的,而且 - 幸运的是 - 你得到了一个编译错误告诉你这一点。
现在说说你的真正问题:
。创建链表数组...
请记住,链表以头元素开头,该元素是"指向节点的指针"。因此,要获取链表数组,您需要一个"指向节点的指针"数组。
例如:
node* arr_of_lists[20];
将是一个具有 20 个"指向节点的指针"的数组。因此,您可以将某些内容用作 20 个链表的数组。
或者采用更像 c++ 的风格:
std::array<node*, 20> arr_of_lists;
或者使用动态分配,以便您可以在运行时控制数组大小:
node** arr_of_lists = new node*[desired_size];
从用户读取数据时,需要两个信息:
1( 要添加的节点的数据值
2( 将节点添加到哪个(例如 20 个(链表。
喜欢:
cin >> data;
cin >> list_index;
// Skipping error checks here... but must be added to the real code
// You need a function like this to creat an new node holding
// data and insert the new node to the linked list at index "list_index"
list_insert(arr_of_lists, list_index, data);