单链表插入
#include <stdlib.h>
#include <stdio.h>
#define FALSE 0
#define TRUE 1
typedef struct NODE {
struct NODE* link;
int value;
} Node;
int sll_insert(register Node **linkp, int new_value)
{
register Node* current;
register Node* new;
while ((current = *linkp) != NULL && current->value < new_value)
{
linkp = ¤t->link;
}
new = (Node*)malloc(sizeof(Node));
if (new == NULL)
return FALSE;
new->value = new_value;
new->link = current;
*linkp = new;
return TRUE;
}
双链表插入
int dll_insert(Node *rootp, int value)
{
Node* this;
Node* next;
Node* newnode;
/*查看value值是否位于链表之中,是返回,否则创建一个新节点
this为新节点前一个结点,next为新节点的后一个节点
*/
for (this = rootp; (next = this->fwd) != NULL; 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;
if (next != NULL) {
if (this != rootp) /*插入到链表中间位置*/
{
newnode->fwd = next;
this->fwd = newnode;
newnode->bwd = this;
next->bwd = newnode;
}
else /*插入到链表的起始位置*/
{
newnode->fwd = next;
rootp->fwd = newnode;
next->bwd = newnode;
newnode->bwd = NULL;
}
}
else
{
/*插入位置在链表结束位置*/
if (this != rootp)
{
newnode->fwd = NULL;
this->fwd = newnode;
newnode->bwd = this;
rootp->bwd = newnode;
}
else
{
newnode->fwd = NULL;
rootp->fwd = newnode;
newnode->bwd = NULL;
rootp->bwd = newnode;
}
}
return 1;
}
将if-else语句中相同的提取出来,得到简化版
int dll_insert(Node rootp, int value)
{
Node this;
Node* next;
Node* newnode;
/*查看value值是否位于链表之中,是返回,否则创建一个新节点
this为新节点前一个结点,next为新节点的后一个节点
/
for (this = rootp; (next = this->fwd) != NULL; 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;
if (next != NULL) {
newnode->fwd = next;
if (this != rootp) /*插入到链表中间位置*/
{
this->fwd = newnode;
newnode->bwd = this;
}
else /*插入到链表的起始位置*/
{
rootp->fwd = newnode;
newnode->bwd = NULL;
}
next->bwd = newnode;
}
else
{
newnode->fwd = NULL;
/*插入位置在链表结束位置*/
if (this != rootp)
{
this->fwd = newnode;
newnode->bwd = this;
}
else
{
rootp->fwd = newnode;
newnode->bwd = NULL;
}
rootp->bwd = newnode;
}
return 1;
}
究极简化版
int dll_insert1(Node* rootp, int value)
{
Node* this;
Node* next;
Node* newnode;
/*查看value值是否位于链表之中,是返回,否则创建一个新节点
this为新节点前一个结点,next为新节点的后一个节点
*/
for (this = rootp; (next = this->fwd) != NULL; 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;
if (this != rootp)
{
this->fwd = newnode;
newnode->bwd = this;
}
else
{
newnode->bwd = NULL;
rootp->fwd = newnode;
}
if (next != NULL) {
next->bwd = newnode;
}
else
{
rootp->bwd = newnode;
}
return 1;
}