# 插入节点的链接列表问题 [英] Linked list problem to insert a node

### 问题描述

Programming Problems and Competitions :: HackerRank[^]

What I have tried:

``````/*
Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
Node* Insert(Node *head,int data)
{
// Complete this method
Node *temp;
temp=head;
if(temp=='\0'){
temp=(struct Node *)malloc(sizeof(struct Node));
temp->data=data;
head=temp;
head->next='\0';
}

else {
while (temp!='\0'){
temp=temp->next;
}
temp->data=data;
temp->next='\0';
}

return head;
}``````

### 推荐答案

Quote：

else {

while（temp！='\ 0'）{

temp = temp-> next;

}

temp-> data = data;

temp-> next ='\ 0';

}

else {
while (temp!='\0'){
temp=temp->next;
}
temp->data=data;
temp->next='\0';
}

Should be, instead

``````else
{
while ( temp->next )
{
temp = temp->next;
}
temp->next = (struct Node *)malloc(sizeof(struct Node));
temp->next->data = data;
temp->next->next = NULL;
}``````

• ` nullptr `（而不是`'\ 0'`` NULL。`
• ` new `而不是` malloc `
• ` Node `构造函数来初始化它。

• Please note, in `C++` code, use:

• `nullptr` (instead of `'\0'` or `NULL.`)
• `new` instead of `malloc`.
• `Node` constructor to initialize it.

• 这篇关于插入节点的链接列表问题的文章就介绍到这了，希望我们推荐的答案对大家有所帮助，也希望大家多多支持IT屋！