【问题标题】:singly linked list simulated with dynamic arrays用动态数组模拟的单链表
【发布时间】:2023-03-29 03:48:02
【问题描述】:

我的代码假设使用节点数组创建一个单链表。

每个节点都有变量 item 保存数据和变量 next 保存列表中下一个节点的索引。最后一个节点在其下一个数据字段中具有 -1 以模拟 nullptr。 head 保存列表中第一个节点的索引。

由于某种原因,当我创建一个指向数组中某个节点的指针时,它会给出以下错误:

错误:初始化时无法将“Node”转换为“Node*”|

 #include "ArrayList.h"
 #include <iostream>
 using namespace std;

ArrayList::ArrayList(char ch){
    array = new Node[Size];
    (array[0]).item = ch;
    (array[0]).next = 1;

    free = 1;
    head = 0;
  }

int ArrayList::length() const{
    if (head == -1) return 0;
    int counter =0;
    Node* current = array[head]; // problem occurs here

while(current->next != -1 ){
    counter++;
    int index = current->next;
    current  = current[index];
}
    counter++;
    return counter;
}

//////////////////

#ifndef ARRAYLIST_H
#define ARRAYLIST_H
#include <iostream>
using namespace std;



class Node{
public:
    char item;
     int next;

    Node(){
        next = -1;
    }
    Node(char input){
        this->item = input;
        next = -1;
    }
};

class ArrayList{
public:

    ArrayList();
    ArrayList(char ch);

    Node& operator[](int index);

    int length() const;
    char getFirst() const;
    void print() const;
private:
    Node* array;
    int  Size = 5;
    int head = -1;
    int free = 0;
};
#endif

/////////////////////

#include <iostream>
#include "ArrayList.h"
using namespace std;

int main(){
    ArrayList list('1');
    list.print();
    return 0;
}

【问题讨论】:

    标签: c++ pointers linked-list dynamic-memory-allocation


    【解决方案1】:

    current 应该是 int 或 size_t,因为代码使用的是索引而不是指针。由于它是一个数组,因此您只能将 new 用于固定最大大小的一次性分配,如果这类似于 std::array。

    【讨论】:

    • 你的想法让我朝着正确的方向前进。你是一个救生员谢谢你
    • @wazeeer - 一旦你让它工作,你可能想尝试实现一个自上而下的合并排序,它只改变下一个索引。它将索引返回到排序列表的“头”,然后 array[head].next 将包含第二个节点的索引,依此类推,直到 array[].next == -1。对于列表,还有另一种自下而上的合并排序,它使用列表头的局部索引数组,其中 array_of_indices[i] 指向具有 pow(2,i) 节点的列表,这更快,但自上而下的版本是更容易理解。
    猜你喜欢
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 2018-01-01
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多