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

查看:61
本文介绍了插入节点的链接列表问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编程问题与竞赛:: HackerRank [ ^ ]



我的尝试:



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;
}









请注意, C ++ 代码,使用:

  • 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆