本章主要介紹了連結清單的相關内容,其中涉及到語句提煉,掌握這種簡化程式的技巧令人向往,當然這需要不斷的學習和實踐。
12.4 簡明的雙向連結清單插入函數
/*
**把一個值插入到雙向連結清單,rootp是一個指向根節點的指針,
**value是欲插入的新值。
**傳回值:如果欲插值原先已存于連結清單中,函數傳回 0;
**如果記憶體不足導緻無法插入,函數傳回-1;如果成功插入,函數傳回1;
連結清單定義如下
typedef struct NODE {
struct NODE *fwd;
struct NODE *bwd;
int value;
} Node;
*/
#include <stdlib.h>
#include <stdio.h>
#include "doubly_linked_list_node.h"
int dll_insert( Node *rootp, int value)
{
Node *this;
Node *next;
Node *newnode;
/*
**檢視value是否已經存在于連結清單中,如果是就傳回。
**否則,為新值建立一個新節點(*newnode 将指向它)
**“this”将指向應該在新節點之前的那個節點
**“that”将指向應該在新節點之後的那個節點
*/
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;
newnode->bwd = NULL;
next->bwd = newnode;
}
}
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;
}
12.5 雙向連結清單插入邏輯的提煉
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;
}
12.6 雙向連結清單插入邏輯的進一步提煉
/*
**把新值添加到連結清單中
*/
newnode->fwd = next;
if(this != rootp)//不在連結清單起始位置的情況
{
this->fwd = newnode;
newnode->bwd = this;
}
else //在連結清單其實位置的情況
{
rootp->fwd = newnode;
newnode->bwd = NULL;
}
if(next != NULL)
next->bwd = newnode;
else
rootp->bwd = newnode;
12.7 雙向連結清單插入函數的最終簡化版本
/*
**把新值添加到連結清單中
*/
newnode->fwd = next;
this->fwd = newnode;
if(this != rootp)
newnode->bwd = this;
else
newnode->bwd = NULL;
if(next != NULL)
next->bwd = newnode;
else
rootp->bwd = newnode;