c - 在链表末尾插入

标签 c data-structures linked-list

我在列表末尾插入节点,但我的代码只打印第一个元素并在无限循环中运行。 我无法找出代码中的错误。

typedef struct nodetype
{
   int info;
   struct nodetype* next;
}node;
node *head=NULL;

void insertatend(int x);//x is the key element.
void print();


void insertatend(int x)
 {
    node *ptr;
    ptr=(node*)malloc(sizeof(node));
    ptr->info=x;
    if(head==NULL)
      {
       ptr->next=ptr;
       head=ptr;
      }
    else
    ptr->next=ptr;
}

void print()   //To print the list
{
   node *temp=head;
   printf("List is-");
   while(temp!=NULL)
   {
      printf("%d",temp->info);
      temp=temp->next;
   }
}

最佳答案

考虑您的插入方法(我将在这里将 head 作为参数而不是全局参数)

void insertatend(node **hd, int x) {
    node *ptr = NULL, *cur = NULL;
    if (!(ptr = malloc(sizeof (node)))) {
        return;
    }
    if (!*hd) {
        *hd = ptr;
    } else {
        cur = *hd;
        while (cur->next) {
            cur = cur->next;
        }
        cur->next = ptr;
    }
}

为了正确执行插入,您需要从头到尾遍历列表。 (因此上面函数中的 while 循环)。

关于c - 在链表末尾插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28498332/

相关文章:

c - C中的函数指针数组

c - 如何在 Visual Studio 2005 中释放动态分配的内存

c - 使用指针传递结构数组时遇到问题

go - 插入一个简单的单链表

c++ - 提高驱动程序的时间效率

c - 由于分配问题导致段错误?

c# - 将数据从平面数组转换为层次结构

java - 从不同文件夹中的所有文件中找出 100 个最大的数字

math - 计算机如何评估巨大的数字?

C链表内存泄漏