双向循环链表
-
基本结构
-
typedef int ElemType;
typedef int DataType;
typedef struct DNode
{
ElemType data;
struct DNode *pre, *next;
}DNode, *DLinkList;
函数
void ListCreate(DLinkList L, int n)
{
int i;
DLinkList p, s;
p = L;
L->pre = L->next = L;
for(i = 0; i < n; i ++)
{
s = (DLinkList)malloc(sizeof(DNode));
scanf("%d", &s->data);
p->next = s;
s->pre = p;
s->next = L;
L->pre = s;
p = s;
}
}
void ListInsert(DLinkList L, int i , ElemType e)
{
DLinkList s, p = L;
while(p->next != L && i > 1)
{
p = p->next;
i--;
}
s = (DLinkList)malloc(sizeof(DNode));
s->data = e;
s->next = p->next;
p->next->pre = s;
s->pre = p;
p->next = s;
}
void ListDelete(DLinkList L, int i, ElemType *e)
{
DLinkList p = NULL, q = L;
while(q->next != L && i >= 1)
{
p = q;
q = q->next;
i--;
}
p->next = q->next;
q->next->pre = p;
*e = q->data;
free(q);
}
void ListTraverse(DLinkList L)
{
DLinkList p = L;
while(p->next != L)
{
p = p->next;
printf("%d", p->data);
}
printf("\n");
}
void ListReTraverse(DLinkList L)
{
DLinkList p = L;
while(p->pre != L)
{
p = p->pre;
printf("%d", p->data);
}
printf("\n");
}
测试代码
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef int DataType;
typedef struct DNode
{
ElemType data;
struct DNode *pre, *next;
}DNode, *DLinkList;
void ListCreate(DLinkList L, int n)
{
int i;
DLinkList p, s;
p = L;
L->pre = L->next = L;
for(i = 0; i < n; i ++)
{
s = (DLinkList)malloc(sizeof(DNode));
scanf("%d", &s->data);
p->next = s;
s->pre = p;
s->next = L;
L->pre = s;
p = s;
}
}
void ListInsert(DLinkList L, int i , ElemType e)
{
DLinkList s, p = L;
while(p->next != L && i > 1)
{
p = p->next;
i--;
}
s = (DLinkList)malloc(sizeof(DNode));
s->data = e;
s->next = p->next;
p->next->pre = s;
s->pre = p;
p->next = s;
}
void ListDelete(DLinkList L, int i, ElemType *e)
{
DLinkList p = NULL, q = L;
while(q->next != L && i >= 1)
{
p = q;
q = q->next;
i--;
}
p->next = q->next;
q->next->pre = p;
*e = q->data;
free(q);
}
void ListTraverse(DLinkList L)
{
DLinkList p = L;
while(p->next != L)
{
p = p->next;
printf("%d", p->data);
}
printf("\n");
}
void ListReTraverse(DLinkList L)
{
DLinkList p = L;
while(p->pre != L)
{
p = p->pre;
printf("%d", p->data);
}
printf("\n");
}
int main()
{
DNode L;
int e;
ListCreate(&L, 3);
ListTraverse(&L);
ListInsert(&L, 1, 0);
ListTraverse(&L);
ListInsert(&L, 5, 7);
ListTraverse(&L);
ListDelete(&L, 1, &e);
ListTraverse(&L);
ListDelete(&L, 4, &e);
ListTraverse(&L);
ListReTraverse(&L);
}