链表--结构与指针使用
2013-11-27 16:24
204 查看
单链表
插入到有序单链表。函数的参数是一个指向链表根指针的指针,以及一个需要插入的新值。
对上面程序的优化:
通过这种优化便可消除插入位置在第一个节点的特殊情况
插入到有序单链表。函数的参数是一个指向链表根指针的指针,以及一个需要插入的新值。
#include <stdlib.h> #include <stdio.h> #define FALSE 0 #define TRUE 1 typedef struct NODE { struct NODE *link; int value; } int sll_insert( Node **rootp, int new_value ) { Node *current; Node *previous; Node *new; current = *rootp; previous = NULL; while( current != NULL && current->value < new_value ) { previous = current;//保存前一个节点地址 current = current->link;//指向下一个节点 } new = (Node *)malloc( sizeof( Node ));//分配动态内存 if( new == NULL ) return FALSE; new->value = new_value;//插入的新值存储在新节点中 //新节点插入链表 new->link = current; if( previous == NULL )//检查是否为第一个节点 *rootp = new; else previous->link = new; return TRUE; }
对上面程序的优化:
#include <stdlib.h> #include <stdio.h> #define FALSE 0 #define TRUE 1 typedef struct NODE { struct NODE *link; int value; } int sll_insert( register Node **linkp, int new_value )//增加 register 声明,提高结果代码效率 { register Node *current; register Node *new; while( ( current = *linkp ) != NULL && current->value < new_value ) linkp = ¤t->link;//linkp是link的地址 new = (Node *)malloc( sizeof( Node ) ); if( new == NULL ) return FALSE; new->value = new_value; //插入新节点到链表,而无需考虑是否是第一个节点 new->link = current; *linkp = new; return TRUE; }
通过这种优化便可消除插入位置在第一个节点的特殊情况
相关文章推荐
- 第十三周——数组大折腾(二)
- cocos2d-x 3.0创建新项目
- 用消息队列和消息应用状态表来消除分布式事务
- c打印字符 '是'
- Tomcat 映射虚拟目录
- nagios外部插件nrpe安装
- IP与子网掩码:深度讲解子网中网络号与主机号的计算方法
- 鼠标右键打开dos窗体
- SSH Secure File Transfer 在linux下 中文乱码的解决办法
- Android开发环境搭建
- Windows系统开机自动运行程序和自动启动服务
- 在ubuntu下编译安装内核及其卸载
- awk substr 左、右取字符
- android获取string.xml的值
- ios开发(四):基本语法 Objects, Classes, and Messaging
- 【mysql】1206 SQLSTATE: HY000 (ER_LOCK_TABLE_FULL) 问题
- Output of C++ Program | Set 14
- 纯虚函数与抽象类
- 调用插件命令时是否需要加 /NOUNLOAD
- 比特币网络的弱点(二)