带有向量的链表



我试图通过对向量的链表执行某些操作。

我们得到了一个结构类型vector
typedef struct{
int *array;   // a pointer to vector's storage
int size;     // the current number of elements in the vector
int cap;      // the current capacity of the vector;
int init_cap; // the initial capacity the vector was initialised with.
} vector;

现在,我想创建一个函数,它接受一个指向vector结构体的指针,并用给定的容量初始化它。所有字段都要初始化。我想使用链表。

这是我的代码

#include <iostream>
using namespace std;
typedef struct node {
int *array;     // a pointer to the vector's storage
int size;       // the current number of elements in the vector
int cap;        // the current capacity of the vector
int init_cap;   // the initial capacity the vector was initialised with
node *next;
} vector;
node *head = NULL;

我可以从一个向量结构中制作节点,就像我在上面写的代码中一样?

void vector_init(vector *v, int capacity){
//initialising the vector with the given capacity
v->size     = capacity;
v->cap      = capacity;
v->init_cap = capacity;
//linked list with nodes created and values initialised
node *temp, temp2;
temp = head;
temp = new node;
temp->size     = capacity;
temp->cap      = capacity;
temp->init_cap = capacity;

temp->next = temp2
temp2 = new node;
temp2->size     = capacity;
temp2->cap      = capacity;
temp2->init_cap = capacity;
    temp2->next = NULL;
}

我是否制作了链表,并正确初始化了值?如果我们不创建临时点temp和temp2,而只是使用v->size等来初始化字段,这会使它成为链表吗?

你的代码有很多问题。

  • 不要使用vector这个名字——有一个叫做std::vector的结构,它很容易被混淆。
  • 如果你想初始化结构的值,不要为此创建一个外部的、单独的函数——这不是c++的风格。创建一个初始化所有值的构造函数。
  • 在代码的任何地方都不要初始化数组变量。您应该根据构造函数中给出的容量为它分配空间。
  • 不要使用'array'作为变量名。c++中有一个叫做std::array的结构,它可能会让人感到困惑。
  • 你的实现对我来说意义不大。你现在有一个数组链表;如果你想用链表替换 int数组,每个节点应该包含一个int值。
  • 如果出于某种原因,您希望坚持这种实现,您还需要某种更新函数,该函数可以在向数组添加或删除元素时自动更新sizecap变量。否则你最终肯定会忘记它你的结构就会一团糟。让这个函数成为结构的一部分——它不应该是外部函数。
  • typedef struct node即使在将vector这个词更改为其他东西之后也没有意义-无论如何你都不会在代码中使用它。
  • 您在两个不同的结构中使用相同的名称;vector首先定义为具有4个字段,在接下来的行中定义为具有5个字段。

技术上是的,这是一个链表,但是你的vector_init()函数不能正常工作。除了我上面写的:

    你应该避免让函数依赖于全局变量,在这种情况下。可以作为参数传递。这两行:

temp = head

temp = new node;

没有意义。第一个使变量temp指向;第二个命令告诉temp在使用operator new时开始指向新变量,该操作分配空间并返回指向新创建变量的指针。因此,当您进行进一步操作时,您不操作变量头,而是操作另一个变量,该变量在temp指针失效后将丢失。

  • 根本不需要temptemp2变量。

  • 这两行

temp->next = temp2;

temp2 = new node;

应该转换位置,因为现在您分配的指针尚未初始化。

    在写完所有这些东西之后,我意识到这个函数通常是不正确的。由于某种原因,您首先处理参数v,然后做一些与之无关的事情。

而且,你的老师说你可以用链表解决所有类型的问题是不对的。它可能在某些情况下解决一些问题,也可能产生新的问题,这取决于上下文。

我不想无礼,但你被赋予的任务本身的概念似乎有根本的问题。

最新更新