以下是本人对双向链表的相关操作及相应的代码优化学习笔记
1 双向链表的插入有4种情况:
1.1 插入到链表的开始位置
1.2 插入到链表的中间位置
1.3 插入到链表的结束位置
1.4 链表为空,既插入到开始位置 同时也插入到结束位置。
1.5 以下是双向链表的示意图:
根据分析,写出代码如下:
代码 1 :
#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