无法插入链接列表

时间:2015-11-29 16:53:23

标签: c pointers linked-list

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

#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 个答案:

答案 0 :(得分:0)

  1. 它的C程序请妥善分类。
  2. 在代码中不使用任何C ++模块。
  3. 使用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);

相关问题