#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *prior,*next;
}*dlinklist,dlistnode;
#define N sizeof(dlistnode)
dlinklist create_dlist(int a)//创建只有一个元素的双向链表
{
dlistnode *head = (dlinklist)malloc(N),*p;
p = (dlinklist)malloc(N);
p->data = a;
p->next = NULL;
p->prior = head;
head->next = p;
head->prior = NULL;
return (head);
}
void insert_dlist(dlinklist head, int e,int n)//插入
{
dlinklist p = head,q;
while(n --)
p = p->next;
q = (dlinklist)malloc(N);
q->data = e;
q->prior = p->prior;
q->next = p;
p->prior->next = q;
p->prior = q;
}
int locate(dlinklist head,int a)//定位
{
dlinklist p = head;
int i = 0;
while(p->next!=head)
{
i ++;
p = p->next;
if(p->data == a)
break;
}
if(p->data != a)
i = 0;
return i;
}
void del_dlist(dlinklist head,int n)//删除
{
dlinklist p = head;
while(n --)
p = p->next;
p->prior->next = p->next;
p->next->prior = p->prior;
free(p);
}
void print_dlist(dlinklist head)//双向输出
{
dlinklist p,q;
p = q = head;
printf("寻找后继输出\t");
while(p->next && p->next != head)//寻找直接后继输出
{
p = p->next;
printf("%d ",p->data);
}
printf("\n");
printf("寻找前驱输出:\t");
while(p->prior != head)//寻找直接前驱输出
{
printf("%d ",p->data);
p = p->prior;
}
printf("%d\n\n",p->data);
}
void circulate(dlinklist head)//构建循环
{
dlinklist p = head;
while(p->next)
{
p = p->next;
}
p->next = head;
head->prior = p;
}
void print_circulate_dlist(dlinklist head,int n)//循环输出
{
dlinklist p;
while(n --)
{
p = head;
while(p->next != head)
{
p = p->next;
printf("%d ",p->data);
}
}
printf("\n\n");
}
int main()
{
int a[9] = {1,2,3,4,5,6,7,8,9};
int n,i;
char ch;
dlinklist head;
head = create_dlist(0);
printf("初始链表为:\n");
print_dlist(head);
printf("是否进行插入操作?y/n\n");
scanf("%c",&ch);
getchar();
if(ch == 'y')
{
printf("调用插入函数,将1--9的元素插入链表\n");
for(i = 0;i < 9;i ++)
{
insert_dlist(head,a[i],1);
printf("插入%d后\n",i+1);
print_dlist(head);
}
}
printf("是否构成循环链表?y/n \n");
scanf("%c",&ch);
if(ch == 'y')
{
circulate(head);
printf("构建成功!尝试循环输出,请输入循环次数\n");
scanf("%d",&n);
print_circulate_dlist(head,n);
}
getchar();
printf("是否进行删除操作?y/n\n");
scanf("%c",&ch);
if(ch == 'y')
{
printf("调用删除函数,删除表中5---9的元素\n\n");
int loc;
for(i = 5;i < 10;i ++)
{
loc = locate(head,i);
if(!loc)
{
printf("表中没有值为%d的元素\n",i);
continue ;
}
del_dlist(head,loc);
printf("删除%d后\n",i);
print_dlist(head);
}
}
printf("操作结束!\n");
printf("当前表的状态为\n");
print_dlist(head);
system("PAUSE");
return 0;
}
双向循环链表
最新推荐文章于 2022-03-21 08:00:00 发布