[英]Linked list implementation segmentation fault
I have done basic implementation of Linked List but its giving Segmentation fault on uncommenting the commented lines otherwise its working fine. 我已经完成了链接列表的基本实现,但它在取消注释注释行时给出了Segmentation错误,否则它的工作正常。 I am not able to understand why its giving the error. 我无法理解为什么它会给出错误。 Please give me some help 请给我一些帮助
void insert(Node **head, Symbol sym) {
Node *temp, *p = *head;;
Symbol a = sym;
temp = (Node *)malloc(sizeof(Node));
temp->value = a;
temp->next = NULL;
if (p == NULL)
*head = temp;
else {
while (p->next != NULL)
p = p->next;
p->next = temp;
}
}
void printList(Node *head) {
Node *p = head;
if(p == NULL) return;
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
printf("\n");
}
int main() {
Node *List, *list2;
insert(&List, 0);
insert(&List, 1);
//insert(&list2, 2);
//insert(&list2, 3);
printList(List);
return 0;
}
You did not initialize initial pointers to nodes 您没有初始化节点的初始指针
Node *List, *list2;
Write 写
Node *List = NULL, *list2 = NULL;
Take into account that variable list2
is not used in the program you showed. 考虑到变量list2
未在您显示的程序中使用。
The other way to write function insert
is the following 编写函数insert
的另一种方法如下
void insert( Node **head, Symbol sym )
{
Node *temp = malloc( sizeof( Node ) );
if ( temp != NULL )
{
temp->value = sym;
temp->next = NULL;
while ( *head ) head = &( *head )->next;
*head = temp;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.