思维导图
1> 思维导图
2> 实现双向循环链表的 创建、判空、尾插、遍历、尾删、销毁
double_looplist.h代码:
#ifndef __DOUBLE_LOOPLIST_H__
#define __DOUBLE_LOOPLIST_H__
#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct double_node
{
union
{
int length;
datatype data;
};
struct double_node *next;
struct double_node *prior;
}double_node,*node_p;
node_p create_double_list();//创建双向循环链表
int empty(node_p H);//判空
node_p create_node(datatype data);//创建普通节点
void insert_tail(node_p H,datatype data);//尾插
void show_double_list(node_p H);//遍历
void delete_tail(node_p H);//尾删
void free_double_list(node_p H);//释放双向循环链表
#endif
double_looplist.c代码:
#include "double_looplist.h"
//创建双向循环链表
node_p create_double_list()
{
node_p H=(node_p)malloc(sizeof(double_node));
if(NULL == H)
{
printf("创建双向循环链表失败!\n");
return NULL;
}
H->length=0;
H->next=H;
H->prior=H;
printf("双向循环链表创建成功!\n");
return H;
}
//判空
int empty(node_p H)
{
if(NULL == H)
{
printf("双向循环链表不合法!\n");
return -1;
}
return H->length==0?1:0;
}
//创建普通节点
node_p create_node(datatype data)
{
node_p N=(node_p)malloc(sizeof(double_node));
if(NULL == N)
{
printf("创建节点失败!\n");
return NULL;
}
N->data=data;
N->next=NULL;
N->prior=NULL;
return N;
}
//尾插
void insert_tail(node_p H,datatype data)
{
if(NULL == H)
{
printf("插入失败!\n");
return;
}
node_p N=create_node(data);
node_p p=H;
while(p->next!=H)
{
p=p->next;
}
N->next=p->next;
N->prior=p;
p->next->prior=N;
p->next=N;
H->length++;
}
//遍历
void show_double_list(node_p H)
{
if(NULL == H || empty(H))
{
printf("遍历失败!\n");
return;
}
node_p p=H;
while(p->next!=H)
{
p=p->next;
printf("%d ",p->data);
}
putchar(10);
}
//尾删
void delete_tail(node_p H)
{
if(NULL == H || empty(H))
{
printf("删除失败!\n");
return;
}
node_p p=H;
for(int i=0;i<H->length-1;i++)
{
p=p->next;//找到要删除节点的上一个节点
}
node_p q=p->next;//要删除的节点
p->next=q->next;
q->next->prior=p;
free(q);
q=NULL;
H->length--;
}
//释放双向循环链表
void free_double_list(node_p H)
{
if(NULL == H)
{
printf("释放失败!\n");
return;
}
node_p p=H;
while(p->next!=H)
{
delete_tail(H);
}
free(H);
H=NULL;
printf("成功释放双向循环链表!\n");
}
main.c代码:
#include "double_looplist.h"
int main(int argc, const char *argv[])
{
node_p H=create_double_list();
insert_tail(H,10);
insert_tail(H,20);
insert_tail(H,30);
insert_tail(H,40);
insert_tail(H,50);
insert_tail(H,60);
insert_tail(H,70);
show_double_list(H);
delete_tail(H);
show_double_list(H);
delete_tail(H);
show_double_list(H);
free_double_list(H);
H=NULL;
return 0;
}