#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct snode{
int data;
struct snode *pre,*next;
}Snode,*LinkList;
LinkList Find(LinkList Head_node,int k);
LinkList InitList()
{
LinkList Head_node=(Snode*)malloc(sizeof(Snode));
if(Head_node==NULL)
{
printf("申请空间失败,即将退出!\n");
return NULL;
}
Head_node->next=Head_node;
Head_node->pre=Head_node;
// return Head_node;
}
void Head_Insert(LinkList Head_node,int e)
{
Snode* new_node=(Snode*)malloc(sizeof(Snode));
if(new_node==NULL)
{
printf("申请空间失败,即将退出\n");
return ;
}
//这里已经写了很多遍,看不懂的可以看看前面的双向链表的代码,有详解
new_node->data=e;
new_node->next=Head_node->next;
new_node->pre=Head_node;
Head_node->next->pre=new_node;
Head_node->next=new_node;
}
void Tail_Insert(LinkList Head_node,int e)
{
Snode* new_node=(Snode*)malloc(sizeof(Snode));
if(new_node==NULL)
{
printf("申请空间失败,即将退出\n");
return ;
}
//这里相当于双向链表的插法,可以去看看前面的代码
Snode* Tail_node=Head_node->pre;
new_node->data=e;
new_node->next=Tail_node->next;
new_node->pre=Tail_node;
Tail_node->next->pre=new_node;
Tail_node->next=new_node;
}
//在值为k的结点后面插
void Val_Insert(LinkList Head_node,int k,int e)
{
Snode* new_node=(Snode*)malloc(sizeof(Snode));
if(new_node==NULL)
{
printf("申请空间失败,即将退出\n");
return ;
}
Snode* p=Find(Head_node,k);//查询k的结点
if(p==NULL)
{
return ;
}
new_node->data=e;
new_node->next=p->next;
new_node->pre=p;
p->next->pre=new_node;
p->next=new_node;
}
LinkList Find(LinkList Head_node,int k)
{
if(Head_node->next==Head_node&&Head_node->pre==Head_node)
{
printf("空链表\n");
return NULL;
}
for(Snode* i=Head_node->next;i!=Head_node;i=i->next)
{
if(i->data==k)
{
return i;
}
}
printf("未找到值为k的结点\n");
return NULL;
}
void Delete(LinkList Head_node,int e)
{
Snode* p=Find(Head_node,e);
if(p==NULL)
{
return ;
}
p->pre->next=p->next;
free(p);
}
void MK_Empty(LinkList Head_node)
{
Snode* Last=Head_node->next;
Snode* Front;
while(Last!=Head_node)
{
Last->next->pre=Last->pre;
Front=Last->next;
free(Last);
Last=Front;
}
Head_node->next=Head_node;
Head_node->pre=Head_node;
}
void PrintfList(LinkList Head_node)
{
if(Head_node->next==Head_node&&Head_node->pre==Head_node)
{
printf("空链表\n");
}
for(Snode* i=Head_node->next;i!=Head_node;i=i->next)
{
printf("%d ",i->data);
}
printf("\n");
}
int main(void)
{
LinkList Head_node=InitList();//创建头结点
Head_Insert(Head_node,1);
Head_Insert(Head_node,2);
Head_Insert(Head_node,3);
Head_Insert(Head_node,4);
PrintfList(Head_node);
Tail_Insert(Head_node,5);
PrintfList(Head_node);
Val_Insert(Head_node,4,6);
PrintfList(Head_node);
Delete(Head_node,3);
PrintfList(Head_node);
MK_Empty(Head_node);
PrintfList(Head_node);
return 0;
}
运行结果