1. 单链表P235~245
1.1 单链表的结构
typedef struct NODE{
STRUCT NODE *link;
int value;
}Node;
//根指针只是一个指针
//链表最后一个节点的指针字段的值为NULL
1.2 单链表的插入P244
int insert_list(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;
}
2. 双链表
对if循环的代码简化
在函数中各个嵌套的if语句群存在相似代码的时候,可以将语句提炼到if循环外
if(x == ){
i = ;
something;
j = ;
}else{
i = ;
something else;
j = ;
}
//修改后
i = ;
if(x == ){
something;
}else{
something else;
}
j = ;
双链表插入结点的相关代码P252
#include <stdio.h>
#include <stdlib.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"将指向它)
//"this"将指向应该在新节点之前的那个节点
//"next"将指向应该在新节点之后的那个节点
for(This = rootp; (next = this->fwd) != NULL; this = next){
if(next->value == value){
return ;
}
if(next->value > value){
break;
}
}
//为新的节点申请空间
newnode = (Node *)malloc(sizeof(Node));
if(newnode == NULL){
return -;
}
newnode->value = value;
//把新节点添加到链表中
newnode->fwd = next;
this->value = value;
if(this != rootp){
newnode->bwd = this;
}else{
newnode->bwd = NULL;
}
if(next != NULL){
next->bwd = newnode;
}else{
rootp->bwd = newnode;
}
return -;
}
3. 语句简练是一种简化程序的技巧,其方法是消除程序中冗余的语句。如果一句if语句的“then”和“else”子句以相同序列的语句结尾,它们可以被一份单独的出现于if语句之后的拷贝代替。相同序列的语句也可以从if语句的起始位置提炼出来,但是这种提炼不能改变if的测试结果。
2016.10.13