#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);
}
}
}