如何使用带有链接列表的node * create语句?

时间:2019-04-05 03:11:39

标签: c++ linked-list

有人可以解释一下下面的代码中“ node * create(int element)”到底是什么意思。我认为它看起来像一个函数,但我不确定。 我也发表了一些评论,以便大家对我的理解有所了解。感谢您提供的任何帮助。

#include <iostream>
using namespace std;

struct node { // linear linked list

  int e;  //data
  node *next; //pointer to itself 

};

node *create(int);    

int main() {
  //edited I think I got it thanks for commenting any advice is welcome
  node *myPtr = NULL;
  myPtr = create(8);

  cout << myPtr -> e;

}



node *create(int element) { //is this a function ?

  //all this comments below is what I deduce so far
  node *n;  //declare node pointer
  n = new node;   //create node
  n->e = element;  //makes 
  n->next = NULL ;  //makes pointer null
  return n;   //returns node

}

2 个答案:

答案 0 :(得分:0)

您对函数中发生的事情的评论是准确的。
您对该功能的使用也很准确。

但是,您仅创建了一个可能是链表的节点。要创建链接列表,您还需要更多。您需要能够创建多个节点并将它们链接在一起。

手工完成:

node* n1 = create(8);
node* n2 = create(10);
node* n3 = create(15);
node* n4 = create(20);
node* n5 = create(30);
node* n6 = create(40);

n1->next = n2;
n2->next = n3;
n3->next = n4;
n4->next = n5;
n5->next = n6;

通过手动编码每个节点的创建来创建这样的链接列表,每个链接变得乏味。将LinkedList创建为类,并在该类中具有成员函数以对该类的对象执行各种操作将是正确的方法。

答案 1 :(得分:0)

node* create(int element) // yes, it is a function
{
  node* n = new node;
  n->e = element;
  n->next = nullptr;
  return n;
}

调用create()时,将在 使用new进行堆,并返回指向该节点的指针 与return n

myPtr指向该节点。

如果要添加更多节点,则需要执行 更多的工作,即具有指向第一个元素的指针 在列表中,然后将节点追加到该列表中。

为节点初始化创建一个构造函数很有帮助 成员变量,而不是在外部进行

struct node
{
   int e;
   node* next;

   node(int v) : e(v), next(nullptr) 
   {}
};

所以而不是

n = new node;
n->e = element;
n->next = nullptr;

您现在可以写

n = new node(element);
相关问题