#include "double_list.h"
//创建双向链表空间
node_p create_double()
{
node_p H = (node_p)malloc(sizeof(node));
if(H==NULL)
{
printf("空间申请失败\n");
return NULL;
}
H->data = 0;
H->next = NULL;
H->pre = NULL;
return H;
}
//创建结点
node_p create_node(int data)
{
node_p new = (node_p)malloc(sizeof(node));
if(new==NULL)
{
printf("空间申请失败\n");
return NULL;
}
new->data = data;
return new;
}
//判空
int empty_double(node_p H)
{
if(H==NULL)
{
printf("入参为空\n");
return -1;
}
return H->next==H?1:0;
}
//头插
void insert_head(node_p H,int data)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
if(empty_double(H))
{
printf("链表为空\n");
return;
}
node_p new = create_node(data);
//双向链表的头插
new->next = H->next;
if(H->next!=NULL)
{
H->next->pre = new; //H->next可能为空
}
new->pre = H;
H->next = new;
H->data++;
}
//输出
void show_node(node_p H)
{
if(H==NULL)
{
printf("入参为空,请检查\n");
return;
}
if(empty_doud(H))
{
printf("链表为空\n");
return;
}
node_p p = H->next;
while(p!=NULL)
{
printf("%d->",p->data);
p=p->next;
}
printf("NULL\n");
}
//头删
void delete_head(node_p H)
{
if(H==NULL)
{
printf("入参为空请检查\n");
return;
}
if(empty_double(H))
{
printf("链表为空\n");
return;
}
node_p del=H->next;
if(H->next!=NULL)
{
H->next->next->pre = H;
H->next = H->next->next;
}
else
{
H->next=NULL;
}
free(del);
H->data;
}
//尾插
void insert_tail(node_p H,int data)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
node_p p=H;
while(p->next!=NULL)
{
p=p->next;
}
node_p new=cread_node(data);
new->next=p->next;
p->next=new;
new->pre=p;
H->data++;
}
//尾删
void delete_tail(node_p H)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
if(empty_doud(H))
{
printf("链表为空\n");
return;
}
node_p p = H;
while(p->next!=NULL)
{
p = p->next;
}
node_p del = p->next;
p->pre->next=NULL;
free(del);
H->data--;
}
//按位置插入
void insert_pos(node_p H,int data,int pos)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
if(pos<=0||pos>H->data+1)
{
printf("位置不合理\n");
return;
}
node_p p=H;
for(int i=0;i<pos-1;i++)
{
p = p->next;
}
node_p new = create_node(data);
if(p->next!=NULL)
{
new->next = p->next;
p->next->pri=new;
}
new->pri=p;
p->next=new;
H->data++;
}
//按位置删除
void delete_pos(node_p H,int pos)
{
if(H==NULL)
{
printf("入参为空\n");
return;
}
if(empty_double(H))
{
printf("链表为空\n");
return;
}
if(pos<=0||pos>H->data)
{
printf("位置不合理\n");
return;
}
node_p p=H;
for(int i=0;i<pos-1;i++)
{
p=p->next;
}
node_p new = p->next;
if(p->next->next!=NULL)
{
p->next->next->pri=p;
}
p->next=p->next->next;
free(new);
H->data--;
}
//双向链表逆置
void overturn(node_p H)
{
if(H==NULL)
{
printf("参数为空\n");
return;
}
if(empty_double(H))
{
printf("链表为空,无需逆置\n");
return;
}
if(H->next->next==NULL)
{
printf("只有一个元素,无需逆置\n");
return;
}
node_p p=H->next->next;
H->next->next=NULL;
while(p!=NULL)
{
node_p q=p->next;
p->next=H->next;
H->next->pri=p;
p->pre=H;
H->next=p;
p=q;
}
【无标题】
最新推荐文章于 2024-06-14 21:55:04 发布
本文介绍了如何使用C语言实现双向链表,包括创建节点、判断链表空、头插、尾插、头删、尾删、按位置插入和删除以及链表逆置等基本操作。
摘要由CSDN通过智能技术生成