双向循环链表
双向循环链表:结构最复杂,一般用在单独存储数据。实际中使用的链表
数据结构
,都是带头
双向循环链表。另外这个链表虽然结构复杂,但是使用代码实现以后会发现能带来很多优势。
双向循环链表的设计:
(1)
动态申请一个结点
(2)
创建头结点进行初始化
(3)
尾插法
(4)
尾删法
(5)
头插法
(6)
头删法
(7)
查找元素
(8)
在
pos
位置前进行插入
(9)
删除
pos
位置的结点
(10)
打印数据
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node{
int date;
struct node *next;
struct node *front;
}linke;
linke *give_a_node(int d){
linke *node = (linke *)malloc(sizeof(linke));
node->front = node->next = NULL;
node->date = d;
return node;
}
linke *init(){
linke *p = give_a_node(0);
p->front = p->next = p;
return p;
}
void linke_put_wei(linke *p, int d){
linke *new = give_a_node(d);
linke *wei = p->front;
wei->next = new;
new->front = wei;
new->next = p;
p->front = new;
}
void linke_del_wei(linke *p){
linke *wei = p->front;
linke *wei_front = wei->front;
wei_front->next = p;
p->front = wei_front;
free(wei);
wei = NULL;
}
void linke_put_tou(linke *p, int d){
linke *new = give_a_node(d);
linke *tou = p->next;
p->next = new;
new->next = tou;
new->front = p;
tou->front = new;
}
void linke_del_tou(linke *p){
linke *tou = p->next;
linke *tou_next = tou->next;
p->next = tou_next;
tou_next->front = p;
free(tou);
tou = NULL;
}
linke *linke_find(linke *p, int d){
linke *node = p->next;
while(node != p){
if(node->date == d){
return node;
}
node = node->next;
}
return NULL;
}
void linke_getin(linke *p, int d){
linke *new = give_a_node(d);
linke *p_front = p->front;
p_front->next = new;
new->next = p;
new->front = p_front;
p->front = new;
}
void linke_del(linke *p){
linke *p_front = p->front;
linke *p_next = p->next;
p_front->next = p_next;
p_next->front = p_front;
free(p);
p = NULL;
}
void linke_p(linke *p){
linke *node = p->next;
while(node != p){
if(node->next == p){
printf("%d",node->date);
}
else{
printf("%d<->",node->date);
}
node = node->next;
}
printf("\n");
}
void Test01()
{
linke *p = init(); //创建一个双向循环链表的头结点
linke_put_wei(p, 1); //用尾插法插入1
linke_put_wei(p, 2); //用尾插法插入2
linke_put_wei(p, 3); //用尾插法插入3
linke_put_wei(p, 4); //用尾插法插入4
linke_p(p); //打印链表中的元素
linke_del_wei(p); //用尾删法删除一个元素
linke_del_wei(p); //用尾删法删除一个元素
linke_del_wei(p); //用尾删法删除一个元素
linke_p(p);
linke_put_tou(p, 1); //用头插法插入1
linke_put_tou(p, 2); //用头插法插入2
linke_put_tou(p, 3); //用头插法插入3
linke_put_tou(p, 4); //用头插法插入4
linke_p(p);
linke_del_tou(p); //用头删法删除一个元素
linke_del_tou(p); //用头删法删除一个元素
linke_del_tou(p); //用头删法删除一个元素
linke_p(p);
}
void Test02()
{
linke *p = init();
linke_put_wei(p, 1);
linke_put_wei(p, 2);
linke_put_wei(p, 3);
linke_put_wei(p, 4);
linke_p(p);
linke *node = linke_find(p, 3);
linke_getin(node, 30);
linke_p(p);
linke_del(node);
linke_p(p);
}
int main()
{
Test01();
Test02();
}