一、向一个有序单链表中插入数据
参数说明:proot :单链表的根指针,注意仅仅是一个指针,不包含数据,指向单链表的第一个结点(第一个包含数据的结点)
value :待插入的数据
struct node {
struct node *link;
int value;
}
struct node *sll_insert(struct node **proot, int value)
{
register struct node *current = NULL;
register struct node **linkp = proot;
register struct node *new = NULL;
while (NULL != (current = *linkp) && current->value < value) {
linkp = ¤t->link;
}
if (NULL == (new = (struct node *)malloc(sizeof(struct node)))) {
return NULL;
}
new->value = value;
new->link = current;
*linkp = new;
return *proot;
}
调用: struct node *root = NULL;
sll_insert(&root, value);
二、向双向链表中插入一个数据,要分为四种插入情况
参数: proot: 双链表的根结点,注意根结点不带数据,
value :待插入的数据
struct node {
struct node *before;
struct node *forward;
int value;
};
struct node *dll_insert(register struct node **proot, int value )
{
register struct node *this = *proot;
register struct node *next = NULL;
register struct node *new = NULL;
while (NULL != (next = this->forward) && next->value < value ) {
this = next;
}
if (NULL == (new == (struct node *)malloc(sizeof(struct node)))) {
return NULL;
}
new->value = value;
new->forward = next;
this->forward = new;
if (this != proot) { // 插入位置不在起始处
new->before = this;
} else { // 插入位置在起始处
new->before = NULL;
}
if (NULL != next) { // 插入位置不在链表末尾
next->before = new;
} else { // 插入位置在链表末尾,
proot->before = new;
}
}
以上为第12章 “使用结构体”一章, 未完待续。。。