[英]how to insert into the singly linked list using double pointers?
键盘链接 我正在尝试使用双指针插入链接列表。但我不明白我要去哪里错了我在堆栈溢出时跟踪了其他链接,我什至还提到了几本书,所以请帮帮我。我保存了代码用于在位置1插入。在输出中,先前的插入丢失。
struct node
{
int data;
node *next;
};
void insert(node **head,int k,int pos)//k refers to the element to be inserted
{
if(pos==1)
{
node *newnode=(node *)malloc(sizeof(node));
newnode->data=k;
newnode->next=*head;
*head=newnode;
}
}
void print(node **head)
{
printf("the elements are.. ");
while(*head!=NULL)
{
printf("%d ",(*head)->data);
(*head)=(*head)->next;
}
printf("\n");
}
int main()
{
insert(&head,5,1);
print(&head);
insert(&head,4,1);
print(&head);
return 0;
}
抱歉缩进不良。我是初学者,请帮助我。
您的打印功能不正确。 您正在擦除行中的头部(*head)=(*head)->next;
。 将功能更改为
void print(node **head)
{
printf("the elements are.. ");
node *temp = *head;
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
您将收到以下输出:
元素是.. 5
元素是.. 4 5
看一下这个。
struct node //Missed struct's name
{
int data;
node *next;
};
void insert(node **head,int k,int pos)//k refers to the element to be inserted
{
if(pos==1)
{
node *newnode= new node();
newnode->data=k;
newnode->next=*head; //You called head which is not a member of node's struct
*head=newnode;
}
}
int main()
{
node *head=NULL;
insert(&head,5,1);
insert(&head,4,1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.