gpt4 book ai didi

c - C 中带头节点的链表

转载 作者:太空宇宙 更新时间:2023-11-03 23:43:34 25 4
gpt4 key购买 nike

The type definition of the list is in linkedList.h as usual.

 #ifndef LINKEDLIST_H
#define LINKEDLIST_H

typedef struct snode {
int value;
struct snode *next;
} snodeType;

typedef struct hnode {int count;
snodeType *first;
snodeType *last;
} sList;

sList* create_sList(void);
int insert_element_s(sList *L, snodeType *p, int value);
int delete_element_s(sList *L, snodeType *p);
sList* merge_lists(sList *L1, sList *L2);

#endif /* LINKEDLIST_H */

问题是:

sList * create_sList(void) creates the list and returns it to the caller. It has to allocate memory for the header node, initialize the fields in the struct hnode.

sList* create_sList(void) {

sList *list = NULL;
list->first = (sList*)malloc(sizeof(snodeType));
list->last = (sList*)malloc(sizeof(snodeType));

/* 2nd option
sList *list = NULL;
node = malloc(sizeof(snodeType));
node->next= NULL;
list->first = node;
list->last = node;
*/

return list;
}

我只需要启动这个链表,有人知道怎么做吗?

最佳答案

那应该只是:

sList * create_sList(void)
{
sList *list = malloc(sizof *list);
if(list != NULL)
{
list->count = 0;
list->first = list->last = NULL;
}
return list;
}

这将返回一个没有元素的列表头,即一个空列表头。

关于c - C 中带头节点的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39615012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com