#include typedef struct dnode
{
int data;
struct dnode *prior;
struct dnode *next;
}dnode;
dnode *add(dnode *dhead);
dnode *del(dnode *dhead);
void printdnode(dnode *dhead);
int main()
{
int sel=0;
dnode *dhead=NULL;
while(1)
{
printf("\t1:添加\n\t2:删除\n\t3:查看\n\t4:退出\n");
scanf("%d",&sel);
switch(sel)
{
case 1:
dhead=add(dhead);
printdnode(dhead);
break;
case 2:
dhead=del(dhead);
printdnode(dhead);
break;
case 3:
printdnode(dhead);
break;
case 4:
exit(0);
default:
printf("reinput 1-4\n");
break;
}
}
return 0;
}
dnode *add(dnode *dhead)
{
int x=0;
dnode *s=NULL;
dnode *p=NULL;
printf("请输入节点数据:\n");
scanf("%d",&x);
s=(dnode *)malloc(sizeof(dnode));
s->data=x;
if(NULL==dhead)
{
dhead=s;
s->next=s;
s->prior=s;
}
else
{
p=dhead;
//先找到添加的位置
while(1)
{
if(s->data>p->data)
{
p=p->next;
if(p==dhead)
{
break;
}
}
else
{
break;
}
}
//插入到p节点的前面
p->prior->next=s;
s->prior=p->prior;
s->next=p;
p->prior=s;
}
return dhead;
}
dnode *del(dnode *dhead)
{
int x=0;
dnode *p=NULL;
if(NULL==dhead)
{
printf("dlist empty\n");
return NULL;
}
printf("请输入删除的数据:\n");
scanf("%d",&x);
p=dhead;
//找到需要删除数据的地址
while(1)
{
if(p->data==x)
{
break;
}
p=p->next;
if(p==dhead)
{
printf("no this data in dlist\n");
return dhead;
}
}
if(dhead==p)
{
dhead=dhead->next;
}
p->prior->next=p->next;
p->next->prior=p->prior;
if((dhead->next==dhead)&&(dhead->prior=dhead)&&(dhead->data==x))
{
free(dhead);
dhead=NULL;
p=NULL;
}
else
{
free(p);
p=NULL;
}
return dhead;
}
void printdnode(dnode *dhead)
{
if(NULL==dhead)
{
printf("dlist empty\n");
return;
}
dnode *p=NULL;
p=dhead;
while(1)
{
printf("%d ",p->data);
p=p->next;
if(p==dhead)
{
break;
}
}
printf("\n");
}