可以通过组合使用结构和指针创建强大的数据结构。
链表(linked list)是一些包含数据的独立数据结构(通常称为节点)的集合。链表中的每个节点通过链或指针连接在一起。程序通过指针访问链表中的节点。通常节点是动态分配的,但有时你也能看到由节点数组构建的链表。
书中给出的单链表的优秀实现为:
#include <stdlib.h>
#include <stdio.h>
# define FALSE 0
# define TRUE 1
typedef struct NODE{
struct NODE *link;
int value;
} Node;
int sll_insert(Node **linkp, int new_value)
{
Node *current;
Node *new;
// 寻找正确的插入位置 直到到达一个其值大于或等于新值的节点
while ((current=*linkp) != NULL && current->value < new_value)
{
linkp = ¤t->link;
}
// 为新节点分配内存 并把新值存储到新节点中
// 如果内存分配失败 函数返回FALSE
new = (Node *)malloc(sizeof(Node));
if (new == NULL)
{
return FALSE;
}
new-value = new_value;
// 在链表中插入新节点 并返回TRUE
new->link = current;
*linkp = new;
return TRUE;
}
书中给出的双链表的优秀实现为:
#include <stdlib.h>
#include <stdio.h>
typedef struct NODE{
struct NODE *fwd;
struct NODE *bwd;
int value;
} Node;
int dll_insert(Node *rootp, int value)
{
Node *this;
Node *next;
Node *newnode;
// 查看value是否已经在链表中 如果是就返回
// 否则为新值创建一个新节点(newnode将指向它)
for (this=rootp; (next=this->fwd) != NULLL; this=next)
{
if (next->value == value)
{
return 0;
}
if (next->value > value)
{
break;
}
}
newnode = (Node *)malloc(sizeof(Node));
if (newnode == NULL)
{
return -1;
}
newnode->value = value;
// 把新节点添加到链表中
newnode->fwd = next;
this->fwd = newnode;
newnode->bwd = this!=rootp ? this : NULL;
(next!=NULL ? next : rootp)->bwd = newnode;
return 1;
}