#include<stdio.h>
#include<stdlib.h>
//双向链表结构
struct dlist
{
int data;
struct dlist *front;//指向下一结点的指针
struct dlist *back;//指向前一结点的指针
};
typedef struct dlist dnode;
typedef dnode *dlink;
dlink createdlist(int *array,int len)
{
dlink head;
dlink before;
dlink new_node;
int i;
//创建第一个结点,分配指针内存
head=(dlink)malloc(sizeof(dnode));
if(!head)
return NULL;
head->data=array[0];
head->front=NULL;
head->back=NULL;
before=head;//指向第一个结点
for(i=1;i<len;i++)//用循环创建其他结点
{
new_node=(dlink)malloc(sizeof(dnode));
if(!new_node)
return NULL;
new_node->data=array[i];
new_node->front=NULL;
new_node->back=before;//将新结点指向前结点
before->front=new_node;//将前结点指向新结点,构成循环链表
before=new_node;//新结点成为前结点
}
return head;
}
//双向链表的输出
void printdlist(dlink head,dlink now)
{
while(head!=NULL) //链表循环遍历
{
if(head == now)
printf("#%d#",head->data);
else
printf("[%d]",head->data);
head=head->front;
}
printf("\n");
}
void main()
{
dlink head;
dlink now=NULL;
int list[6]={1,2,3,4,5,6};
int select;
head=createdlist(list,6);
if(head==NULL)
{
printf("内存分配失败!\n");
exit(1);
}
now=head;
while(1)
{
printf("链表内容是:");
printdlist(head,now);
printf("[1]往下移动 [2]往回移动 [3]离开 ==> ");
scanf("%d",&select);
switch(select)
{
case 1: if(now->front!=NULL)
now=now->front;
break;
case 2: if(now->back!=NULL)
now=now->back;
break;
case 3: exit(1);
}
}
}