这不是程序的最终实现,但程序本身有点长,所以我决定改为以小块的形式创建它。我遇到了一个错误,上面写着
函数 list_first 的隐式声明。
还有其他错误需要解决,但我想先获得一些帮助,然后自己处理其余的错误,尽管如果你愿意,欢迎你提供额外的帮助。这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
// The type for a node in the list.
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 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;
}
static void add_values(List *lst)
{
ListPos pos = list_first(lst);
pos = list_insert(pos, "Apple");
pos = list_next(pos);
pos = list_insert(pos, "Banana");
pos = list_next(pos);
pos = list_insert(pos, "Citrus");
}
ListPos list_end(List *lst)
{
ListPos pos = {
.node = &lst->head
};
return pos;
}
ListPos list_first(List *lst)
{
ListPos pos = {
.node = lst->head.next
};
return pos;
}
ListPos list_next(ListPos pos)
{
struct node* node;
//pos = node -> next;
struct node *before = pos.node->prev;
struct node *after = pos.node;
node->next = after;
after->prev = node;
pos.node = node;
return pos;
}
ListPos list_insert(ListPos pos, const char *value)
{
// Create a new node.
struct node *node = make_node(value);
// Find nodes before and after (may be the same node: the head of the list).
struct node *before = pos.node->prev;
struct node *after = pos.node;
// Link to node after.
node->next = after;
after->prev = node;
// Link to node before.
node->prev = before;
before->next = node;
// Return the position of the new element.
pos.node = node;
return pos;
}
int main(void)
{
// Create an empty list.
List *lst = list_create();
add_values(lst);
return 0;
}