链表中的各对象按线性顺序排列,而其顺序是由各个对象里的指针所决定的。
链表有多种形式,它可以是单链接的或者双链接的,可以是已排序的或未排序的,可以是循环的或非循环的。
定义的结构体以及函数如下:
typedef struct SINGLE_LINKED_LIST
{
Node * head;
Node * tail;
} SLL;
typedef struct CIRCULAR_SINGLE_LINKED_LIST
{
Node * head;
Node * tail;
} CSLL;
typedef struct DOUBLE_LINKED_LIST
{
Node * head;
Node * tail;
} DLL;
typedef struct CIRCULAR_DOUBLE_LINKED_LIST_WITH_SENTINEL
{
Node * nil;
} CDLLS;
void linked_list_traverse(Node * L);
void linked_list_free(Node* L);
Node* single_linked_list_insert(SLL * L, item_t item);
Node* single_linked_list_search(SLL * L, item_t item);
int single_linked_list_delete(SLL * L, Node * node);
Node* circular_single_linked_list_insert(CSLL * L, item_t item);
Node* circular_single_linked_list_search(CSLL * L, item_t item);
int circular_single_linked_list_delete(CSLL * L, Node * node);
Node* double_linked_list_insert(DLL * L, item_t item);
Node* double_linked_list_search(DLL * L, item_t item);
int double_linked_list_delete(DLL * L, Node * node);
CDLLS* circular_double_linked_list_with_sentinel_init();
Node* circular_double_linked_list_with_sentinel_insert(CDLLS * L, item_t item);
Node* circular_double_linked_list_with_sentinel_search(CDLLS * L, item_t item);
int circular_double_linked_list_with_sentinel_delete(CDLLS * L, Node * node);
几个公共函数如下:
//functions for all kind of linked list
void linked_list_traverse(Node* L) {
if (L == NULL) {
printf("Empty Linked List.\n");
}
Node * pos = L;
while (pos != NULL) {
printf("%2d is in location:%9p. prev is %9p. next is %9p.\n", pos->item.key, \
pos, pos->prev, pos->next);
pos = pos->next;
if (pos == L) return;
}
}
void linked_list_free(Node* L) {
Node * pos = L;
Node * f = L;
while (pos != NULL && pos != L) {
f = pos;
pos = pos->next;
free(f);
}
}
//-----------------------------------------------------------------------
单链接的未排序非循环链表可以如如下实现:
//functions for single linked list
Node* single_linked_list_insert(SLL * L, item_t item) {
Node * node = (Node*)malloc(sizeof(Node));
node->item = item;
node->prev = NULL;
node->next = L->head;
if (L->tail == NULL)
L->tail = node;
L->head = node;
return node;
}
Node* single_linked_list_search(SLL * L, item_t item) {
if (L->head == NULL) {
fprintf(stderr, "The single linked list is empty.\n");
return NULL;
}
Node * pos = L->head;
while (pos != NULL) {
if (item.key == pos->item.key)
return pos;
pos = pos->next;
}
fprintf(stderr, "The item cannot be found.\n");
return NULL;
}
int single_linked_list_delete(SLL * L, Node * node) {
if (L->head == NULL) {
fprintf(stderr, "The single linked list is empty.\n");
return 0;
}
if (node == NULL) {
fprintf(stderr, "The node is NULL.\n");
return 0;
}
if (L->head == node) {
L->head = node->next;
if (L->head == NULL)
L->tail = NULL;
return 1;
}
Node * pos = L->head;
while (pos != NULL && pos->next != node) {
pos &#