双向循环带头链表的逻辑结构如下所示:(下面便简称双向链表)
本次将实现:
1、双向链表的节点创建,链表创建
2、链表初始化
3、头插尾插操作
4、头删尾删操作
5、任意位置删除以及任意位置前插入操作
6、查找、打印、清空操作
实现一:双向链表节点的创建,链表的创建:
typedef struct node {
int val;
struct node* prev;
struct node* next;
}node;
typedef struct list{
struct node* head;
}list;
struct node* Creatnode(int x){
struct node* node = (struct node*) malloc(sizeof(struct node));
node->next = NULL;
node->prev = NULL;
node->val = x;
return node;
}
实现二:链表的初始化;
void InitList(list* s) {
struct node* node = (struct node*) malloc(sizeof(struct node));
s->head = node;
node->next = node;
node->prev = node;
}
实现三:头插、尾插操作;
//头插操作
void ListPushFront(list* s,int x) {
struct node* cur = s->head;
struct node* node = Creatnode(x);
node->next = cur ->next;
cur->next->prev = node;
cur->next = node;
node->prev = cur;
}
//尾插操作
void ListPushBack(list* s, int x) {
struct node* cur = s->head;
struct node* node = Creatnode(x);
node->next = cur;
node->prev = cur->prev;
cur->prev->next = node;
cur->prev = node;
}
实现四:头删、尾删操作;
//尾删操作
void ListPopBack(list* s) {
//保留头节点
if (s->head->next == s->head) {
return;
}
else {
struct node* cur = s->head->prev;
cur->prev->next = cur->next;
cur->next->prev = cur->prev;
free(cur);
cur = NULL;
}
}
//头删操作
void ListPopFront(list* s) {
if (s->head->next == s->head) {
return;
}
else {
struct node* cur = s->head->next;
cur->prev->next = cur->next;
cur->next->prev = cur->prev;
free(cur);
cur = NULL;
}
}
实现五:任意位置删除以及任意位置前插入操作;
//给定位置的前面插入
void ListInsert(node* pos, int x) {
struct node* node = Creatnode(x);
node->next = pos;
node->prev = pos->prev;
pos->prev->next = node;
pos->prev = node;
}
node* ListFind(list* s, int x) {
if (s->head == s->head->next) {
return NULL;
}
else {
node* cur = s->head->next;
while (cur != s->head){
if (cur->val == x) {
return cur;
}
else cur = cur->next;
}
return NULL;
}
}
//任意位置删除操作
void ListErase(node* pos) {
if (pos->next == pos) {
return;
}
else {
pos->next->prev = pos->prev;
pos->prev->next = pos->next;
free(pos);
}
}
实现六:查找、打印、清空操作
//打印函数
void ListPrint(list* s) {
struct node* cur = s->head;
while (cur->next != s->head) {
cur = cur->next;
printf("%d ", cur->val);
}
printf("\n");
}
//查找函数
node* ListFind(list* s, int x) {
if (s->head == s->head->next) {
return NULL;
}
else {
node* cur = s->head->next;
while (cur != s->head){
if (cur->val == x) {
return cur;
}
else cur = cur->next;
}
return NULL;
}
}
//清空操作
void Dele(list* s) {
while (s->head != s->head->next)
ListPopBack(s);
free(s->head);
s->head = NULL;
}