双向链表基本操作及代码优化技巧

以下是本人对双向链表的相关操作及相应的代码优化学习笔记

双向链表的插入有4种情况:

1插入到链表的开始位置

1插入到链表的中间位置

1插入到链表的结束位置

1链表为空,既插入到开始位置 同时也插入到结束位置。

1.5 以下是双向链表的示意图:


根据分析,写出代码如下:

代码 

#include<stdio.h>
#include<stdlib.h>
typedef struct node {

	struct node *prev;
	struct node *next;
	int 		value;


}Node;

Node *create_node(int value)
{
	
	Node *root =(Node *)malloc(sizeof(Node));
	if (root == NULL)
		return 0;
	root->next = NULL;
	root->prev = NULL;
	root->value = value;
	return root;
}
//此链表有头结点,头结点的prev next 指针分别
//指向第一个结点和最后一个结点
int list_insert1(Node *root,int value)
{
	Node *this;
	Node *that;
	Node *new;
	for (this = root;(that = this->next)!=NULL;
		this = that) {
		if (that->value == value){
			return 1;
		} 
		if (that->value > value) {
			break;
		}
	}
	//跳出for循环的条件是找到了待插入的结点
	//或则是一直没有找到,知道遍历到链表末尾
	//最后把新节点插入尾端
	new = create_node(value);
	//插入到链表开始位置,或则插入在链表中间
	if (that != NULL) {

		//插入起始位置
		if (this ==root) {
			new->next = that;
			root->next = new;
			new->prev = NULL;
			that->prev = new;			

		} else {
			new->next = that;
			this->next =new;
			new->prev = this;
			that->prev =new;
		}
	
	} else { 
		//在链表末尾,  that指针为NULL 时 跳出for循环
		if (this != root) { 
			this->next = new;
			new->next =	NULL;
			new->prev = this;
			root->prev = new;

		} else {  //链表为空
			root->next = new;
			new->next =	NULL;
			root->prev 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值