簡體   English   中英

實現鏈表數組

[英]Implementing an array of linked lists

現在正在處理圖形,並且非常堅持創建一個鏈表數組(鄰接列表),嘗試了一些變體,但出現了這個錯誤:

[錯誤] 'operator>>' 不匹配(操作數類型為 '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];
    }
}

我只會干預你的編譯錯誤,不會干預你需要建立鏈表,因為你的要求不明確。
您必須先為 class 重載運算符>> ,然后才能使用它:

#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;
}

僅定義了節點和圖形(listik)。

在此階段可以修復錯誤:

#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 ();
}

Class 應該添加adjacencyList(鏈表)。

這段代碼:

node **listik;
...
...
    cin >> listik[i];

在兩個方面是錯誤的。

1) listik未初始化,因此listik[i]也是。 換句話說 - 您正在嘗試讀取您的程序(很可能)不擁有的 memory 。

2) 因為listik是一個“指向節點指針的指針”, listik[i]是一個“指向節點的指針”。 要求用戶輸入指針值是沒有意義的,而且 - 幸運的是 - 你得到了一個編譯錯誤告訴你。

現在問你真正的問題:

...創建一個鏈表數組...

請記住,鏈表以 head 元素開始,它是“指向節點的指針”。 所以要得到一個鏈表數組,你需要一個“指向節點的指針”數組。

例如:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM