第十二章 使用结构和指针 [c和指针]
来源:互联网 发布:网络有真的恋人吗 编辑:程序博客网 时间:2024/06/13 17:05
本章主要介绍了链表的相关内容,其中涉及到语句提炼,掌握这种简化程序的技巧令人向往,当然这需要不断的学习和实践。
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;
- 第十二章 使用结构和指针 [c和指针]
- 第十二章 使用结构和指针
- 《C和指针》第十二章 使用结构和指针和第十七章 经典抽象数据类型
- 《C和指针》第12章 使用结构和指针
- C和指针读书笔记(第十二章)
- C和指针读书笔记——使用结构和指针
- 使用结构和指针
- 《c和指针》第十二章单链表练习
- 《c和指针》第十二章双链表练习
- C和指针读书笔记-第12章(使用结构和指针)
- c指针和结构体
- 《C和指针》:结构和联合
- C和指针详解------结构和联合
- 读书笔记---C和指针---第十章---结构和联合
- 记录-C和指针-第十章-结构和联合
- C语言结构体和指针
- C语言结构体和指针
- c语言 -- 指针和结构体
- android小贴士
- 基于FBX SDK的FBX模型解析与加载 -(四)
- fedora 16 安装 texlive 2011
- linux
- 硬盘结构,主引导记录MBR,硬盘分区表DPT,主分区、扩展分区和逻辑分区
- 第十二章 使用结构和指针 [c和指针]
- C++ 字符串操作函数集合(部分)
- Linux系统引导过程及硬盘分区结构论述
- synchronized同步机制
- TCP详解
- Linux命令行报bash:.....:command not found的解决办法
- 为firefox的搜索栏添加baidu搜索
- CLR概述
- python学习系列之OS模块介绍