【发布时间】:2016-05-09 13:40:19
【问题描述】:
我正在尝试学习链接列表中的插入技术。在执行期间,每次说程序停止工作时它都会崩溃。它没有显示任何错误。我是 Stack Overflow 的新手。如果这个问题已经被问过,请原谅我。这是我的代码:
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
void push(struct node** head_ref, int new_data)
{
struct node* new_node= (struct node*)malloc(sizeof(struct node));
new_node->data=new_data;
new_node->next=(*head_ref);
(*head_ref)=new_node;
}
void insertAfter(struct node* prev_node, int new_data)
{
if(prev_node==NULL)
{printf("The previous node cannot be NULL");
return;
}
struct node* new_node=(struct node*)malloc(sizeof(struct node));
new_node->data=new_data;
new_node->next=prev_node->next;
prev_node->next=new_node;
}
void append(struct node** head_ref, int new_data)
{
struct node* new_node= (struct node*)malloc(sizeof(struct node));
struct node *last= *head_ref;
new_node->data=new_data;
new_node->next=NULL;
if(*head_ref==NULL)
{
*head_ref=new_node;
}
else
while(last->next!=NULL)
{
last=last->next; /* Segmentation fault */
}
last->next=new_node;
return;
}
void printlist(struct node *node)
{
while(node!=NULL)
{
printf("%d",node->data);
node=node->next;
}
}
int main()
{
struct node* head=NULL;
append(&head,6);
push(&head,7);
push(&head,11);
append(&head,4);
insertAfter(head->next,12);
printf("\n Created Linked list is:");
printlist(head);
return 0;
}
【问题讨论】:
-
使用调试器,先缩小有问题的指令范围。
-
好吧,现在它说的是分段错误。你如何解决这个问题? (对不起,我还是编程新手)
-
您的代码的某些格式也不会出错。
-
我们需要知道错误发生在哪里...
-
请注意
(struct node*)malloc(sizeof(struct node));强制转换是不必要的,并且可能会掩盖类型错误。
标签: c data-structures linked-list insertion