#include<stdio.h>
#include<stdlib.h>
typedef struct XNode
{
int data;
struct XNode *next,*perior;
}XNode,*XLinklist;
void Init_head(XNode *&L) //头插法创建链表
{
L=(XLinklist)malloc(sizeof(XNode));
L->next=NULL;
L->perior=NULL;
int x=0;
XNode *s,*p=L->next,*q;
printf("请输入x:\n");
scanf("%d",&x);
while(x!=999)
{ s=(XLinklist)malloc(sizeof(XNode));
s->data=x;
if(L->next==NULL)
{
L->next=s;
s->perior=L;
L->perior=s;
s->next=L;
}
else
{
s->next=L->next;
s->perior=L;
L->next->perior=s;
L->next=s;
}
printf("请输入x:\n");
scanf("%d",&x);
}
}
void Init_end(XNode *&L) //尾插法
{
L=(XLinklist)malloc(sizeof(XNode));
L->next=NULL;
L->perior=NULL;
int x=0;
XNode *s,*p;
printf("请输入x:\n");
scanf("%d",&x);
while(x!=999)
{
s=(XLinklist)malloc(sizeof(XNode));
s->data=x;
if (L->next==NULL)
{
L->next=s;
s->perior=L;
L->perior=s;
s->next=L;
}
else
{
p=L->perior;
s->perior=p;
p->next=s;
s->next=L;
L->perior=s;
}
printf("请输入x:\n");
scanf("%d",&x);
}
}
bool insert(XLinklist &L,int e) //将元素插入第e个位置
{
int x,i=1;
XLinklist p=L->next,s,q;
s=(XLinklist)malloc(sizeof(XNode));
printf("请输入x:\n");
scanf("%d",&x);
s->data=x;
while(p!=NULL)
{
if(i==e)
{
s->next=p;
s->perior=p->perior;
p->perior->next=s;
p->perior=s;
return true;
}
else
{
p=p->next;
i++;
}
}
if(i==e)
{
L->perior->next=s;
s->perior=L->perior;
L->perior=s;
s->next=L;
return true;
}
return false;
}
void print(XNode *L) //遍历输出
{
XNode *p=L->next;
while(p!=L)
{
printf("%d ",p->data);
p=p->next;
}
}
bool deletelist(XNode *&L,int e) //删除第e个位置的元素
{
int i=1;
XLinklist p=L->next,q=L->perior;
while (p!=L)
{
if(i==e)
{
if(p->next==L)
{
L->perior=p->perior;
p->perior->next=L;
free(p);
}
else
{
p->perior->next=p->next;
p->next->perior=p->perior;
free(p);
}
break;
}
else
{
p=p->next;
i++;
}
}
}
int main()
{
XLinklist L1,L2;
Init_head(L1);
print(L1);
printf("======\n");
Init_end(L2);
print(L2);
printf("------\n");
insert(L1,4);
print(L1);
printf("******\n");
deletelist(L2,3);
print(L2);
}
循环双链表(王道)-----7/15
最新推荐文章于 2023-09-15 10:38:01 发布