添加元素时,我打印出链接列表的头部和尾部,非常简单。
int main(){
struct node{
struct node* next;
struct node* previous;
double value;
};
struct LinkedList{
struct node* head;
struct node* tail;
};
void addValue(struct LinkedList* list,double newValue){
struct node newNode;
newNode.next = NULL;
newNode.value=newValue;
if(list->head == NULL){
newNode.previous=NULL;
list->head= &newNode;
list->tail=&newNode;
}
else
{
newNode.previous= list->tail;
list->tail->next= &newNode;
list->tail= &newNode;
}
printf("%f\n",list->head->value);
printf("%f\n",list->tail->value);
}
struct LinkedList l1;
l1.head=NULL;
l1.tail=NULL;
addValue(&l1,5);
addValue(&l1,6);
addValue(&l1,7);
addValue(&l1,8);
}
但我得到的输出是
5.000000 5.000000 6.000000 6.000000 7.000000 7.000000 8.000000 8.000000
取而代之的是
5.000000 5.000000 5.000000 6.000000 5.000000 7.000000 5.000000 8.000000
知道为什么吗?
答案 0 :(得分:4)
如评论中所述,您应该在堆上创建newNode
。当函数退出时,指针不再指向有效内存。幸运的是,您需要进行的更改很少。
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->next = NULL;
newNode->value=newValue;
if(list->head == NULL){
newNode->previous=NULL;
list->head= newNode;
list->tail=newNode;
}
else
{
newNode->previous= list->tail;
list->tail->next= newNode;
list->tail=newNode;
}
为了避免内存泄漏,你应该free
你的指针。这是一个示例实现:
void deleteList(struct node** head_ref)
{
struct node* current = *head_ref;
struct node* next;
while (current != NULL)
{
next = current->next;
free(current);
current = next;
}
*head_ref = NULL;
}
deleteList(&l1.head);
我在valgrind
进行了测试,这可以消除您的泄漏。
答案 1 :(得分:0)
通过定义struct node newNode;在void addValue(struct LinkedList * list,double newValue)中,内存在堆栈上分配。所以当从函数返回控件时,不再访问堆栈。价值观消失!!!!这需要从堆,动态内存中分配,直到它被释放为止。