Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Data structures 在单链表中插入_Data Structures_Linked List - Fatal编程技术网

Data structures 在单链表中插入

Data structures 在单链表中插入,data-structures,linked-list,Data Structures,Linked List,在单链表中插入以下方法的优缺点是什么 struct node { int data; struct node *next; }; void insert(struct node** head,int val) { struct node *nptr=(struct node*)malloc(sizeof(struct node)); nptr->data=val; nptr->next=*head; *head=nptr; } st

在单链表中插入以下方法的优缺点是什么

struct node
{
    int data;
    struct node *next;
};

void insert(struct node** head,int val)
{
    struct node *nptr=(struct node*)malloc(sizeof(struct node));
    nptr->data=val;
    nptr->next=*head;
    *head=nptr;
}

struct node* insert(struct node *head,int val)
{
    struct node *nptr=(struct node*)malloc(sizeof(struct node));
    nptr->data=val;
    nptr->next=head;
    return nptr;
}
可以在表达式中使用返回node*的函数。例如,为了创建包含2个节点的列表,理论上可以编写:

node* head = insert(insert(NULL, 1), 2);
然而,在现实生活中,您必须检查malloc的返回值。这意味着,两个函数都需要修改以包含此检查。例如,第一个函数的更正确版本是:

bool insert(struct node** head,int val)
{
  struct node *nptr=(struct node*)malloc(sizeof(struct node));
  if (nptr != NULL)
  {
    nptr->data=val;
    nptr->next=*head;
    *head=nptr;
    return true;
  }
  else
  {
    return false;
  }
}
在表达式中使用这些修改过的函数仍然是可能的,但您必须通过调用它们,这将增加表达式的长度和复杂性


至于两种情况下的通话效率,也没有明确的答案。您的代码可能由不同硬件的不同编译器编译—例如,请参阅以更好地了解调用方函数和被调用方函数之间的关系。因此,在某些情况下,第一个函数会快一点,而在其他一些情况下,第二个函数会快一点。有些编译器甚至会将两个函数编译成完全相同的汇编代码

请求对现有工作代码的反馈属于您的职责范围。您的观点是正确的。但我不认为这是问题的意图@anjaneypandey给出了两种在链表中插入的方法,并询问,哪种方法更好更有效,为什么?