我把幾段代碼放在一起做一個鏈接列表,添加到頭部(有一個特殊功能)和中間(也有特殊功能)。 我的問題是,我需要提供數字程序並將它們作爲節點插入到我的LINKEDLIST中。但是,我的顯示功能(顯示節點樹)給出了分段錯誤,因此只是在沒有任何顯示功能的情況下取值。 我對malloc相當陌生,所以我懷疑問題在那裏? 謝謝我的鏈表中的分段錯誤錯誤-C
#include<stdio.h>
#include<stdlib.h>
/*LINKEDLIST STRUCT*/
struct node {
int data;
struct node *next;
};
/*Inserting head-Node*/
struct node *insert_head(struct node *head, int number)
{
struct node *temp;
temp = malloc(sizeof(struct node));
if(temp == NULL)
{
printf("Not enough memory\n");
exit(1);
}
temp->data = number;
temp->next = head;
head = temp;
return head;
}
/*Inserting inside a list*/
void after_me(struct node *me, int number)
{
struct node *temp;
temp = malloc(sizeof(struct node));
if(temp == NULL)
{
printf("Not enough memory\n");
exit(1);
}
temp->data = number;
temp->next = me->next;
me->next = temp;
}
/*PRINTING LIST*/
void display(struct node *head)
{
struct node *moving_ptr = head;
while(moving_ptr != NULL)
{
printf("%d-->",moving_ptr->data);
moving_ptr = moving_ptr->next;
}
}
int main()
{
int index;
struct node *head;
struct node *previous_node;
scanf("%d", &index);
while(index > 0)
{
/*allocating in List */
if(head == NULL)
head = insert_head(head,index);
else
if((head != NULL) && (index <= (head->data)))
{
struct node *temp;
head->next = temp;
temp->next = head;/*TRY INSERT HEAD FUNC.*/
}
else
if((head != NULL) && (index > (head->data)))
{
previous_node->data = index-1;
after_me(previous_node,index);
}
scanf("%d", &index);
}
display(head);
}
也'struct node * temp; head-> next = temp;':'temp'未初始化。 – BLUEPIXY 2015-03-31 22:29:35
'previous_node'尚未初始化或在previous_node-> data = index-1之前分配內存;' – 2015-03-31 22:29:52