#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
typedef int data_t;
typedef struct DNode {
data_t data;
struct DNode *next;
struct DNode *prior;
}DNode, *DouList;
DouList CreateList(void)
{
DouList L = (DouList)malloc(sizeof(DNode));
if(NULL == L)
{
return NULL;
}
L->next = L;
return L;
}
void ClearList(DouList L)
{
DouList p;
while(L->next != L)
{
p = L->next;
L->next = p->next;
free(p);
}
p = NULL;
}
int LengthList(DouList L)
{
int count = 0;
DouList p = L;
while((p->next) != L)
{
p = p->next;
count ++;
}
return count;
}
int IsEmpty(DouList L)
{
if(L->next != L)
{
return FALSE;
}
return TRUE;
}
DouList LocateList(DouList L, data_t x)
{
DouList p = L->next;
while(p != L)
{
if(x == p->data)
{
return p;
}
p = p->next;
}
return NULL;
}
DouList FindList(DouList L, int i)
{
if(i<1 || i>LengthList(L))
{
return NULL;
}
DouList p = L;
int j;
for(j = 0; j < i; j ++)
{
p = p->next;
}
return p;
}
int InsertList(DouList L, data_t x, int i)
{
#if 1
if(i<1 || i>(LengthList(L)+1))
{
return FALSE;
}
#endif
DouList p = L;
int j;
for(j = 1; j < i; j ++)
{
p = p->next;
}
DouList Q = (DouList)malloc(sizeof(DNode));
if(Q != NULL)
{
Q->data = x;
Q->next = NULL;
}
if(1 == i)
{
Q->next = L->next;
Q->prior = L;
L->next->prior = Q;
L->next = Q;
}
else{
Q->next = p->next;
Q->prior = p;
p->next->prior = Q;
p->next = Q;
}
return TRUE;
}
int DleList(DouList L, int i)
{
if(i<1 || i>LengthList(L))
{
return FALSE;
}
DouList p = L;
int j;
for(j = 1; j < i; j ++)
{
p = p->next;
}
DouList q = p->next;
p->next = q->next;
q->next->prior = p;
free(q);
q = NULL;
return TRUE;
}
void DisplayList(DouList L)
{
DouList p = L->next;
while(p != L)
{
printf("%-d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
DouList L = CreateList();
int i;
for(i = 1; i <= 5; i++)
{
InsertList(L, i+2, i);
}
DisplayList(L);
DleList(L, 3);
DisplayList(L);
printf("%d\n", IsEmpty(L));
printf("find 3: %p\n", FindList(L, 3));
printf("locate 3: %p\n", LocateList(L, 3));
printf("locate 7: %p\n", LocateList(L, 7));
printf("length: %d\n", LengthList(L));
ClearList(L);
DisplayList(L);
printf("%d\n", IsEmpty(L));
return 0;
}