【问题标题】:How to insert Node at end of Linked List?如何在链表末尾插入节点?
【发布时间】:2021-05-23 06:53:48
【问题描述】:

我是数据结构的初学者,我想知道如何在链表的末尾插入节点。 使用以下代码,我可以在开头和除链表末尾之外的任何其他位置插入节点。但是在最后插入节点时,我无法这样做。

void Insert(NODE *head,int n,int pos)
{
     NODE  *temp, *newnode;
     int i;
     for(temp = head, i = 1; ( temp != NULL ) && ( i <= pos-1 ); i++)
     {

         if(temp->next==NULL)
         {
             printf("\nPosition is out of range.\n\n");
         }
         

     }
          newnode = (NODE*)malloc(sizeof(NODE));
          newnode->info = n;
          newnode->next = temp->next;
          temp->next = newnode;
}

当我在最后插入节点时,它会给出以下输出 “位置超出范围。” 我有点理解为什么它会给出该输出,但我无法找到我应该如何更改我的代码。 谢谢。

【问题讨论】:

  • 我不敢相信在搜索 [c] How to insert Node at end of Linked List 后返回的众多问题和答案中,连 一个 都没有任何价值。
  • "我可以在链表的开头和结尾插入节点。但是在末尾插入节点时,我无法这样做。"这两句话相互矛盾。
  • 我很抱歉问题中的错误,已经进行了必要的编辑。
  • William Pursell ,我做了必要的修改。

标签: c data-structures linked-list singly-linked-list


【解决方案1】:

评论你的代码:

for(temp = head, i = 1; ( temp != NULL ) && ( i <= pos-1 ); i++)
{

     if(temp->next==NULL) // Adding at the end means that you add when
                          // temp-> next is NULL
     {
         printf("\nPosition is out of range.\n\n");
     }
     

 }

例如,如果您在列表中的一个 1 元素并在位置 2 插入,您将有 (i next==NULL) true。

【讨论】:

    猜你喜欢
    • 2015-12-14
    • 2011-08-13
    • 2020-11-15
    • 2015-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多