c - 无法插入链表

标签 c pointers linked-list

我试图在给定的链表中插入一个元素,但是当我想打印它时,它显示无限循环。在 insert() 调用中,我传递指针的地址,而在显示中,我只传递存储的地址在指针中。请帮助我

#include<stdio.h>
struct node{
int item;
node *ptr;
};
int insert(node **head, int data, int position)
{ 
int count=1;
node *temp=malloc(sizeof(struct node));
temp->item=data;
temp->ptr=NULL;
node *p,*q;
p=*head;
if(*head==NULL)
{
    *head=temp;
}
if(position==1)
{
    temp->item=*head;
    *head=temp;
}
else{
while(p!=NULL&&count<position)
{
    count++;
    q=p;
    p=p->ptr;

}
q->ptr=temp;
temp->ptr=p;
}
}
void display(node *temp)
{
while(temp!=NULL)
{
    printf("the data is %d",temp->item);
    temp=temp->ptr;
}
}
void main()
{
node *head=malloc(sizeof(struct node));
insert(&head,29,1);
display(head);
}

最佳答案

  1. 它是一个C程序,请正确分类。
  2. 您的代码中未使用任何 C++ 模块。

使用 C 实现 -

我认为在简单插入链表时不需要双指针。 你能做的是 -

void insert(node *head, int data){
   node *temp= malloc(sizeof(struct node));
   temp->item = data;
   temp->ptr= NULL;
   if(head==NULL){  //empty list
       head=temp;
   }
   else {
     while(head->ptr!=NULL){ //traverse till end
       head=head->ptr;
     }
     head->ptr=temp;
   }
 }

并从主函数调用 insert(head,value);

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

相关文章:

C - 链表 : free() function is deleting my head node; how do I use free() correctly?

data-structures - 链表和队列有什么区别?

python - 在多路树或连通图中查找一组元素/节点的根元素

c - void* 数组上的交换无法正常工作

c - 读取并收集文本文件中的变量

字符数组显示为空,试图附加第二个字符串

python - 如何通过ID访问变量?

C错误: expression must have arithmetic or pointer type

pointers - 从作为接口(interface)传递的指针连接 slice

c - 使用逻辑运算符和前/后增量无法从此代码中获得预期输出