我在 C 中为我的双链表编写了大部分代码,但似乎我努力将值添加到列表中的原因是由于创建空的双链表时犯了一个错误。
struct node
{
struct node *next;
struct node *prev;
char *value;
};
// The type for a list.
typedef struct list
{
struct node head;
} List;
// The type for a list position.
typedef struct list_pos
{
struct node *node;
} ListPos;
List *list_create(void)
{
List *lst = (List*)malloc(sizeof(List));
if(lst == NULL)
{
printf("No more memory!\n");
return 0;
}
return lst;
}
static struct node *make_node(const char *value)
{
struct node *result = malloc(sizeof(struct node));
result->value = strdup(value);
result -> next = NULL;
result -> prev = NULL;
return result;
}
用法示例:main 函数:List *lst = list_create();
from 函数add_values()
:
static void add_values(List *lst) {
char str[2] = "A";
ListPos pos = list_first(lst);
for (char ch = 'A'; ch <= 'Z'; ch++) {
str[0] = ch;
pos = list_insert(pos, str);
pos = list_next(pos);
}
}
功能实现:
int main(void){
List *lst = list_create();
...
}
add_values static void add_values(List *lst) {
char str[2] = "A"; ListPos pos = list_first(lst);
for (char ch = 'A'; ch <= 'Z'; ch++) {
str[0] = ch;
pos = list_insert(pos, str);
pos = list_next(pos);
}
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(61条)