关于双向链表的解释就不多说了,书本上介绍的挺详细的了,只需要记住每个节点有一个指向下一个节点的指针变量和指向前一个节点的指针变量即可。下面直接上代码。
DualLinkedList.h的代码如下所示:
ifndef DualLinkedList_h
define DualLinkedList_h
include <stdio.h>
endif /* DualLinkedList_h */
typedef struct DualLinkNode{
struct DualLinkNode *per;
struct DualLinkNode *next;
int data;
}DualLinkNode;
typedef DualLinkNode *DualLinkList;
void testDualLinkedList(void);
/**
初始化链表
*/
DualLinkList initDualLinkList(void);
/**
向双向列表中插入数据
*/
int insertData2DualLink(DualLinkList list,int data);
/**
向双向列表中指定位置插入数据
*/
int insertData2DualLinkWithIndex(DualLinkList list,int data,int index);
/**
遍历双向列表
*/
void forEachDualLinkList(DualLinkList list);
/**
清空双向链表
*/
void clearDualLinkList(DualLinkList list);
/**
销毁双向链表
*/
void destoryDualLinkList(DualLinkList *list);
DualLinkedList.c的代码如下所示:
include "DualLinkedList.h"
include "stdlib.h"
void testDualLinkedList(void){
DualLinkList list = initDualLinkList();
for(int i = 1;i<11;i++){
insertData2DualLink(list, i * 10);
}
// forEachDualLinkList(list);
insertData2DualLinkWithIndex(list, 2, 2);
forEachDualLinkList(list);
destoryDualLinkList(&list);
}
DualLinkList initDualLinkList(void){
DualLinkList list = (DualLinkList)malloc(sizeof(DualLinkNode));
if(!list){
printf("链表为空,不能继续运行!\n");
return NULL;
}
list->per = NULL;
list->next = NULL;
return list;
}
int insertData2DualLink(DualLinkList list,int data){
DualLinkList link = (DualLinkList)malloc(sizeof(DualLinkNode));
if(!link){
printf("链表为空,不能继续运行!\n");
return 0;
}
DualLinkList cur = list;
while (cur->next) {//从后边插入
cur = cur->next;
}
link->data = data;
link->next = NULL;
link->per = cur;
cur->next = link;
return 1;
}
int insertData2DualLinkWithIndex(DualLinkList list,int data,int index){
if(!list || data < 0){
return -1;
}
DualLinkList cur = list;
int i = 0;
if(cur->next && i < index - 1){
i++;
cur = cur->next;
}
if(!cur || i > index){
printf("超出链表的最大长度\n");
return -2;
}
DualLinkList link = (DualLinkList)malloc(sizeof(DualLinkNode));
link->data = data;
link->per = cur;
link->next = cur->next;
cur->next->per = link;
cur->next = link;
return 0;
}
void forEachDualLinkList(DualLinkList list){
if(!list){
return;
}
DualLinkList cur = list;
DualLinkList per = list->per;
while (cur->next) {
cur = cur->next;
per = cur->per;
printf("per:%d---next----%d\n",per->data,cur->data);
}
}
void clearDualLinkList(DualLinkList list){
if(!list){
return;
};
DualLinkList p,q;
p = list->next;
while (p) {
q = p->next;
free(p);
p = q;
}
list->next = NULL;
printf("清空结束\n");
}
void destoryDualLinkList(DualLinkList list){
if(!list){
return;
}
clearDualLinkList(list);
free(*list);
*list = NULL;
}