《c和指针》笔记--简洁的单项链表插入操作

单项链表插入操作,我想应该是最基础不过的东西,今天要介绍的是比较简洁的版本。

需求:插入一个node到链表的正确位置,当前链表中节点的value已经按照由小到大进行排列。

传统的插入操作:

int insertNode(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 0;
	new->value = new_value;
	
	new->link = current;
	if(previous == NULL){
		*rootp = new;
	}else{
		previous->link = new;
	}
	
	return 1;
}

上面的算法虽然没有什么问题,但是需要定义current和previous2个变量,

而且需要对插入到第一个node的情况作特殊处理。


下面请看改进版本,只要定义一个current变量,而且不需要插入到第一个node的情况作特殊处理。

int insertNode(Node** linkp,int new_value){
	Node *current;
	Node *new;
	
	while(current = *linkp)!= NULL && current->value < new_value){
		linkp = &t->link;
	}
	
	new = (Node*)malloc(sizeof(Node));
	if(new == NULL)
		return 0;
	new->value = new_value;
	
	new->link = current;
	*linkp = new;
	
	return 1;
}

如果链表开始的状态如下:


可见,new node需要插入到一个表头。

插入前的各指针的状态如下:


插入new node



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值