链表无法插入 [英] Linked List not working for insertion
问题描述
我已经写了一个链表代码来在节点中插入一个元素.但是问题是当我想使用功能插入第一个元素时,输出为空.但是,当我在主函数中插入第一个元素时(请参见注释行),它会提供正确的输出.怎么解决呢?这是我的C代码:
I have written a linked list code to insert a element in the node. But the problem is when i want to insert first element using function, the output is coming empty. But when i insert first element inside the main function (see comment line), it gives the correct output. How to solve it ? Here is my C code:
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int val;
struct node *next;
}node;
void print(node *head){
if(tem == NULL){
printf("List is Empty\n");
return;
}
node *tem= head;
while(tem != NULL){
printf("%d ", tem->val);
tem= tem->next;
}
}
void insert(node *head, int val){
if(head == NULL){
node *tem= malloc(sizeof(node*));
tem->val= val;
tem->next= NULL;
head= tem;
return;
}
node *tem= head;
while(tem->next != NULL){
tem= tem->next;
}
tem->next= malloc(sizeof(node*));
tem->next->val = val;
tem->next->next= NULL;
}
int main()
{
node *head= NULL;
/*
head = malloc(sizeof(node*));
head->val= 5;
head->next= NULL;
*/
insert(head, 15);
print(head);
return 0;
}
谢谢
推荐答案
尝试发送 head
的地址,而不是 head
的地址,如下所示:
Try sending the address of the head
instead of head
as shown below:
insert(& head,15);
void insert(node **head, int val){
if(*head == NULL){
node *tem= malloc(sizeof(node*));
tem->val= val;
tem->next= NULL;
*head= tem;
return;
}
这是因为在发送磁头时,所做的任何更改都将在该函数本地发生(在这种情况下,请插入),并且不会在该函数外部反映出来.因此,您必须发送head(& head
)的地址,以便对head所做的更改也反映在函数外部.干杯
This is because when you are sending the head, any changes made will be local to that function (insert in this case) and won't be reflected outside that function. Hence, you have to send the address of head (&head
) so that changes made to head are reflected outside the function as well. Cheers
这篇关于链表无法插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!