循环双链表
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>
#define random(x) rand() % (x)
typedef int Status;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode* next;
struct LNode* prior;
}*LNode;
typedef struct DoubleLinkList
{
struct LNode* head;
int size;
}DLinkList;
Status InitDLinkList(DLinkList* List);
Status CreateDLinkList(DLinkList* List,int n);
void Traverse(DLinkList List,int visit());
Status Insert(DLinkList* List,int i,ElemType e);
int visit(void* data)
{
printf("%d\t",*(int*)data);
return 1;
}
int main()
{
DLinkList List;
int n = 0;
if(InitDLinkList(&List) == 0)
exit(1);
printf("please input the counter of number");
scanf("%d",&n);
CreateDLinkList(&List,n);
Traverse(List,&visit);
Insert(&List,3,100);
Traverse(List,&visit);
return 0;
}
Status Insert(DLinkList* List,int i,ElemType e)
{
if(i < 1 || i > List -> size + 1)
return 0;
LNode head = List -> head,p = head,pnew = NULL;
int j = 1;
while(p && j < i)
{
p = p -> next;
j++;
}
if((pnew = (LNode) malloc (sizeof(struct LNode))) == 0)
return 0;
pnew -> data = e;
pnew -> next = p -> next;
p -> next -> prior = pnew;
pnew -> prior = p;
p -> next = pnew;
List -> size++;
return 1;
}
Status Delete(DLinkList* List,int i,ElemType* e)
{
if(i < 1 || i > List -> size);
return 0;
LNode head = List -> head,p = head,q = NULL;
int j = 1;
while(p && j < i)
{
p = p -> next;
j++;
}
q = p -> next;
q -> next -> prior = p;
p -> next = q -> next;
*e = q -> data;
free(q);
List -> size--;
return 1;
}
Status CreateDLinkList(DLinkList* List,int n)
{
LNode head = List -> head,p = head,pnew = NULL;;
int i = 0;
srand(time(NULL));
while(i < n)
{
if((pnew = (LNode) malloc (sizeof(struct LNode))) == 0)
return 0;
pnew -> data = random(100);
pnew -> next = p -> next;
p -> next -> prior = pnew;
pnew -> prior = p;
p -> next = pnew;
p = p -> next;
i++;
}
List -> size += n;
return 1;
}
void Traverse(DLinkList List,int visit())
{
LNode head = List.head,p = head -> next;
while(p != head)
{
visit(&p -> data);
p = p -> next;
}
printf("\n");
}
Status InitDLinkList(DLinkList* List)
{
LNode head = NULL;
if((head = (LNode) malloc (sizeof(struct LNode))) == 0)
return 0;
head -> next = head;
head -> prior = head;
head -> data = 0;
List -> head = head;
List -> size = 0;
}