一、简介
关于数据结构学习的相关代码,是本人在学习过程中,完全根据自己的理解所写的一些基本操作,可能会产生一些错误,但本人写博客的原因只为记录一下个人的学习记录,如有读者看到本人博客有错误的地方,请指正。
二、具体实现
#include<stdio.h>
#include<malloc.h>
struct DNode
{
int data;
//prior 指向前一个节点的位置
//next指向后一个节点的位置
DNode *prior, *next;
};
struct LinkDNode
{
int length;//当前链表长度
DNode *head;//头节点
};
//头插法构建双链表
bool buildNode1(LinkDNode *L){
//第一步为头节点分配空间
L->head = (DNode*)malloc(sizeof(DNode));
L->head->prior = NULL;
L->head->next = NULL;
DNode*p = L->head;
DNode *newNode;//要添加的新节点
for (int i = 0; i < 10;i++){
newNode = (DNode*)malloc(sizeof(DNode));
newNode->data = i;
newNode->next = NULL;
newNode->prior = NULL;
newNode->next = p->next;
p->next = newNode;
//L->length记录当前链表的长度
if (L->length>0){
p->next->next->prior = newNode;
//这里如果没有指向头节点的prior指针,下面就可以直接写成
//p->prior!= NULL
//但是我这里加上了指向头指针的节点
//所以写成p->prior->prior!= NULL
newNode->prior = p;
}
newNode->prior = p;
L->length++;
}
return true;
}
//尾插法构建链表
bool buildNode2(LinkDNode *L){
L->head = (DNode*)malloc(sizeof(DNode));
L->head->prior = NULL;
L->head->next = NULL;
L->head->data = NULL;
DNode *newNode;//插入的新结点
DNode *last = L->head;//last尾节点
for (int i = 0; i < 10;i++){
newNode = (DNode*)malloc(sizeof(DNode));
newNode->data = i;
newNode->next = NULL;
newNode->prior = NULL;
last->next = newNode;
newNode->prior = last;
last = newNode;
L->length++;
}
last->next = NULL;
return true;
}
//双链表的插入操作
bool insertEle(LinkDNode *L,int index,int data){
if (index < 0 || index>L->length)
return false;
DNode* newNode = (DNode*)malloc(sizeof(DNode));
newNode->data = data;
newNode->next = NULL;
DNode*p = L->head;
for (int i = 0; i < index - 1;i++){
p = p->next;
}
//注意在插入的时候一定是新节点先指向后一个节点,然偶前一个结点在指向后一个结点
newNode->next = p->next;
p->next = newNode;
newNode->prior = p;//指向前驱
newNode->next->prior = newNode;//新结点的后一个 结点指向前驱
L->length++;
return true;
}
//双链表的删除操作
bool deleNode(LinkDNode *L, int index){
if (L->length == 0)
return false;
if (index < 0||index>L->length-1){
return false;
}
DNode *p = L->head;
for (int i = 0; i < index - 1;i++){
p = p->next;
}
DNode *dNode = p->next;//要删除的结点
p->next = dNode->next;
dNode->next->prior = dNode->prior;
free(dNode);
L->length--;
return true;
}
void show(LinkDNode *L){
DNode *p = L->head;
while (p->next!=NULL)
{
p = p->next;
printf("%d",p->data);
}
//利用双链表的从后往前遍历
printf("利用双链表进行遍历,从后往前");
while (p->prior->prior!= NULL)
{
p = p->prior;
printf("%d", p->data);
}
}
void main(){
LinkDNode link = { 0 };
/*测试头插法
if (buildNode1(&link)){
show(&link);
}
else{
printf("建立链表失败");
}*/
//测试尾插法
if (buildNode2(&link)){
//show(&link);
//测试插入
if (insertEle(&link,2,2)){
show(&link);
}
else{
printf("插入失败");
}
//测试删除
if (deleNode(&link, 2)){
printf(" ");
show(&link);
}
else{
printf("插入失败");
}
}
else{
printf("建立链表失败");
}
}