#include<stdio.h> #include<stdlib.h>
typedef int DataType;
typedef struct node{ struct node *prior;//prior域 struct node *next;//next域 DataType data;//数据域 } DNOList;
void initList(DNOList **head);//Initialization function int length(DNOList *head);//Length function int insertList(DNOList *head,int i,DataType x); //Insert function int DeleteList(DNOList *head ,int i,DataType *x);//Delete function int getElement(DNOList *head,int i,DataType *x);//Get data element void Destory(DNOList **head);//Delete double linked list
int main(void){ DNOList *list; int x; int i;
initList(&list);
for(i=0;i<10;i++)
insertList(list,i,i+1);
//DeleteList(list,0, &x);
int n=length(list);
for(i=0;i<n;i++)
{
getElement(list,i,&x);
printf("%d ",x);
}
printf("\n");
printf("双链表的长度%d\n",length(list));
Destory(&list);
return 0;
}
void initList(DNOList **head){ *head=(DNOList *)malloc(sizeof(DNOList));//Dynamic application address (*head)->next=*head;//The next field of the head pointer points to the head pointer (*head)->prior=*head;//The priority field of the head pointer points to the head pointer }
int length(DNOList *head){ int count=0;//统计数量 DNOList *p=head; while(p->next!=head){ count++; p=p->next; } return count; }
int insertList(DNOList *head,int i,DataType x){ DNOList *p,*q; int j=0; p=head->next;
//find the i-th node while(p!=head&&j<i){ p=p->next; j++; } if(j!=i){ printf("The insertion position is wrong\n"); return 0 ; } q=(DNOList *)malloc(sizeof(DNOList)); q->data=x; q->prior=p->prior;//The predecessor of the new node points to i-1 nodes p->prior- >next=q;//The successor of the i-1 node points to the new node q->next=p;//The successor of the new node points to the i node p->prior=q;//The predecessor of the i node points to the new node printf( "Successful insertion\n"); return 1; }
int DeleteList(DNOList *head,int i,DataType *x){ DNOList *p,*q; int j=-1;//Because it contains a head node, the assignment is -1 p=head;
while(p->next!=head&&j<i){
p=p->next;
j++;
}
if(j!=i){
printf("输入的参数有误\n");
return 0;
}
q=p;
*x=p->data;
p->prior->next=p->next;//i-1的节点的next域指向i+1
p->next->prior=p->prior; //i+1的前驱指向i-1
free(q);
printf("删除成功\n");
return 1;
}
void Destory(DNOList **head){ DNOList *p,*q; p=*head; int n=length(*head);//Seek the length of the single linked list, because it is a circular double linked list, so no while int i; //Set the loop variable for(i=0;i<=n;i++){ q=p; p=p->next; free(q); } *head=NULL; }
int getElement(DNOList *head,int i,DataType *x){ DNOList *p; p=head; int j=-1; while(p->next!=head&&j<i){ j++; p=p->next; }
if(j!=i){ printf("Error taking data element"); return 0; }
*x=p->data; return 1;
}