[英]In the implementation of Linkedlist in C, head is not being set NULL
我正在嘗試使用struct linkslist和struct node (如下實現)在 C 中實現鏈表。
當我調用new_list()
方法時,我明確地將list->head
設置為NULL
。 現在,我嘗試使用add_elem()
方法添加第一個元素。 稍后,我使用print_list()
函數打印列表的第一個元素。
在add_elem()
函數中,我檢查:如果頭部為NULL
並且索引(添加節點的位置)為零,則創建頭部並設置值。 但是,當我執行代碼時, list->head==NULL
是FALSE
。
為什么 head 不是NULL
,即使在明確設置為NULL
之后?
#include<stdio.h>
#include<stdlib.h>
struct node{
int value;
struct node *next;
};
struct linkedlist{
int size;
struct node *head;
};
void new_list(struct linkedlist *input);
int get_elem(struct linkedlist *list, int index);
int add_elem(struct linkedlist *list, int index, int value);
void remove_elem(int index);
void print_list(struct linkedlist *list);
int main(){
struct linkedlist *mylist;
printf("starting the program \n");
// Creating an empty list
new_list(mylist);
int index = 0;
int value = 2;
// adding an element (currently only supports of adding a head)
add_elem(mylist, index, value);
// print the head
print_list(mylist);
return 0;
}
void new_list(struct linkedlist* input){
printf("Creating new list\n");
input = (struct linkedlist*) malloc(sizeof(struct linkedlist));
input->size = 0;
//input->head = (struct node *)malloc(sizeof(struct node));
input->head = NULL;
}
int add_elem(struct linkedlist *list, int index, int value){
// If i remove "list->head==NULL" condition, it works
// otherwise it goes into else block, instead of executing if block
if(list->head==NULL && index==0){
printf("Adding first elem\n");
struct node *nodeptr;
nodeptr =(struct node *) malloc(sizeof(struct node));
nodeptr->value=value;
nodeptr->next = NULL;
list->head = nodeptr;
list->size=1;
return 1;
}
else {
// handle later
return -1;
}
}
void print_list(struct linkedlist *list){
if(list!=NULL && list->head!=NULL){
struct node *ptr = list->head;
//while(ptr!=NULL)
{
printf("Head value:%d\n",ptr->value);
ptr= ptr->next;
}
}
}
編輯:
我按照建議更改了函數 new_list() 以將新分配的地址直接作為返回值返回。 現在代碼可以正常工作了。
struct linkedlist* new_list(void){
printf("Creating new list\n");
return (struct linkedlist*) malloc(sizeof(struct linkedlist));
}
new_list
分配一個新的頭節點,但它分配給input
不改變的值mylist
。 因此, add_elem
不會查看您分配和分配給的節點; 它查看mylist
碰巧指向的任何內容,這可能是任何內容,因為您從未初始化過它(我想,希望new_list
為您做這件事)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.