#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int ElemType;
typedef struct DualNobe
{
ElemType data;
struct DualNobe *prior;
struct DualNobe *next;
} DualNobe, *DuLinkList;
int initList(DuLinkList *L);
int listInsert(DuLinkList *L, int i, int e);
int listDelete(DuLinkList *L, int i, int *e);
int listFree(DuLinkList *L);
int listAdd(DuLinkList *L, int e);
int listPrint(DuLinkList L);
int initList(DuLinkList *L)
{
if (!*L)
{
DuLinkList p;
p = (DuLinkList)malloc(sizeof(DualNobe));
if (!p)
{
return ERROR;
}
*L = p;
p->next = p;
p->prior = p;
return OK;
}
else
{
return ERROR;
}
}
int listAdd(DuLinkList *L, int e)
{
if (!*L)
{
return ERROR;
}
DuLinkList p, cecha = (*L)->prior;
p = (DuLinkList)malloc(sizeof(DualNobe));
if (!p)
{
return ERROR;
}
p->data = e;
cecha->next = p;
p->next = *L;
(*L)->prior = p;
p->prior = cecha;
}
int listPrint(DuLinkList L)
{
DuLinkList p = L->next;
while (p != L)
{
printf("%d ", p->data);
p = p->next;
}
putchar('\n');
return OK;
}
int listInsert(DuLinkList *L, int i, int e)
{
if (i < 1)
{
return ERROR;
}
DuLinkList p, cecha = *L;
p = (DuLinkList)malloc(sizeof(DualNobe));
if (!p)
{
return ERROR;
}
p->data = e;
int j = 1;
while (cecha->next != *L && j < i)
{
cecha = cecha->next;
++j;
}
cecha->next->prior = p;
p->next = cecha->next;
cecha->next = p;
p->prior = cecha;
return OK;
}
int listDelete(DuLinkList *L, int i, int *e)
{
if (i < 1)
{
return ERROR;
}
DuLinkList cecha = *L, p_free = NULL;
int j = 1;
while (cecha->next != *L && j < i)
{
cecha = cecha->next;
++j;
}
if (cecha->next == *L)
{
return ERROR;
}
*e = cecha->next->data;
p_free = cecha->next;
cecha->next = cecha->next->next;
cecha->next->next->prior = cecha;
free(p_free);
return OK;
}
int listFree(DuLinkList *L)
{
DuLinkList cecha = (*L)->next, p_free = NULL;
while (cecha != *L)
{
p_free = cecha;
cecha = cecha->next;
free(p_free);
}
p_free = cecha;
*L = NULL;
free(p_free);
return OK;
}
int main(void)
{
DuLinkList head = NULL;
int e;
initList(&head);
listAdd(&head, 1);
listAdd(&head, 2);
listAdd(&head, 3);
listAdd(&head, 4);
listInsert(&head, 1, 666);
listDelete(&head, 5, &e);
printf("删除 %d\n", e);
listPrint(head);
listFree(&head);
return 0;
}