双向循环链表的基本操作------C语言

#include
#include

typedef int Elemtype;
typedef int Status;

//双向链表存储结构
typedef struct DulNode
{
Elemtype date;
struct DulNode *prior;   /*直接前驱指针*/
struct DulNode *next;    /*直接后继指针*/
}DulNode, *DuLinkList;

//双向循环链表初始化
void DuInitList(DuLinkList L)
{
L = (DulNode *)malloc(sizeof(DulNode));
L->next = L;
L->prior = L;
}

//创建双向循环链表
void DuCreateList(DuLinkList L, int i)
{
DulNode *p, *r;
r = L;
int j = 1;
printf("请输入数据:");
while(j <= i)
{
p = (DulNode *)malloc(sizeof(DulNode));
scanf("%d", &p->date);
r->next = p;
p->prior = r;
r = p;
j++;
}
L->prior = r;
r->next = L;
}

//在p结点后插入结点s
Status DuInsertList(DuLinkList L, Elemtype x, Elemtype e)
{
DulNode *p, *s;
p = L->next;
if(p == L)
return 0;
while(p->next != L && p->date != x)
p = p->next;
if(p->next == L && p->date != x)
return 0;
s = (DulNode *)malloc(sizeof(DulNode));
s->date = e;
s->prior = p;
s->next = p->next;
p->next->prior = s;
p->next = s;
return 1;
}

//删除结点p
Status DuDeleteList(DuLinkList L, Elemtype x, Elemtype *e)
{
DulNode *p;
p = L->next;
if(p == L)
return 0;
while(p->next != L && p->date != x)
p = p->next;
if(p->date != x && p->next == L)
return 0;
p->prior->next = p->next;
p->next->prior = p->prior;
*e = p->date;
free(p);
return 1;
}

void main()
{
DuLinkList L;
int i;
Elemtype e;
DuInitList(L);
printf("请输入元素的个数:");
scanf("%d", &i);
DuCreateList(L, i);
printf("请输入要插入的位置和元素:");
scanf("%d %d", &i, &e);
if(DuInsertList(L, i, e))
{
DulNode *p;
p = L->next;
while(p != L)
{
printf("%d ", p->date);
p = p->next;
}
}
printf("\n请输入要删除的元素:");
scanf("%d", &i);
if(DuDeleteList(L, i, &e))
{
DulNode *p;
p = L->next;
while(p != L)
{
printf("%d ", p->date);
p = p->next;
}
printf("\n删除的元素为%d", e);
}
}

你可能感兴趣的:(数据结构)