【发布时间】:2015-03-31 22:21:31
【问题描述】:
我把几段代码放在一起做一个链表,添加到头部(具有特殊功能)和中间(也有特殊功能)。 我的问题是,我需要为程序提供数字并将它们作为节点插入到我的 LINKEDLIST 中。但是,我的显示功能(显示节点树)会返回分段错误,因此仅在没有任何显示功能的情况下取值。 我对 malloc 还很陌生,所以我怀疑问题出在哪里? 谢谢
#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未初始化。 -
previous_node在previous_node->data = index-1;之前没有被初始化或内存分配
标签: c linked-list malloc