pointers - this指针-C++链表

标签 pointers struct linked-list this

我试图创建一个带有结构的链接列表。这个想法是使用 2 个不同的结构,一个是节点,另一个是指向节点的指针(因此,我可以将节点链接在一起)。

但我想将指向第一个节点的指针初始化为 NULL,并稍后创建后续节点:

我在 2 个构造函数方法(列表和多项式)中遇到错误,我无法像我一样使用运算符 = 。但我不明白为什么。

struct List
{
    //Data members to hold an array of pointers, pointing to a specific node
    Node *list[100];

    //Default constructor
    List();
};

List::List()
{
    *list[0] = NULL;
}

class Polynomial
{
    public:
    [...]

    private:
        List *poly;                         //Store the pointer links in an array
        Node first_node;
        int val;
};

Polynomial::Polynomial()
{
    poly = new List();
}

/*******************************************************************************************************************************/
// Method   : initialize()
// Description  : This function creates the linked nodes
/*******************************************************************************************************************************/
Polynomial::void initialize(ifstream &file)
{
    int y[20];
    double x[20];
    int i = 0, j = 0;

    //Read from the file
    file >> x[j];
    file >> y[j];

    first_node(x[j], y[j++]);                       //Create the first node with coef, and pwr
    *poly->list[i] = &first_node;                       //Link to the fist node

    //Creat a linked list
    while(y[j] != 0)
    {
        file >> x[j];
        file >> y[j];
        *poly->list[++i] = new Node(x[j], y[j++]);
    }

    val = i+1;                              //Keeps track of the number of nodes
}

我在多项式构造函数和列表构造函数中遇到错误。

最佳答案

看起来不像链接列表。也许您需要一个包含信息的 struct node (对吗?),并且 List 包含许多 node ?如果这两个,我有两个解决方案:

首先。非常(而且非常)常见。

typedef struct nNode{
  int info;
  string name;
  //and any information you want this node has.
  struct nNode *pNext;
} Node;

第二。就像我在您的代码中看到的样式。

typedef struct nNode{
  int info;
  string name;
  //and any information you want this node has
}Node;
typedef struct nList{
  Node node;
  struct nList *pNext;
} List;

你看,第二个版本看起来像第一个:)

关于pointers - this指针-C++链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9656867/

相关文章:

c++ - 结构数组的初始化

java - 用两个键映射一个值?

c - 我的 C 程序出了什么问题?这是关于指针和选择排序的

c++ 解决方案在 leetcode 上失败,地址未对齐错误,但在 Visual Studio 中运行

c++ - 第一个索引后未填充结构数组索引

json - Swift JSON 序列化类型不匹配

c++ - Deleting Element from linked list, interviews exposed book bug?

c - c中的链表插入: inserting wrong values

c++ - 指针数组和类型转换

c - 在Eclipse中进行C编程时出现奇怪的行为