数据结构:线性表(循环双链表)C语言简单实现
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define _CRT_SECURE_NO_WARNINGS
#define ok 1
#define error -1
typedef int Elemtype;
typedef int Status;
typedef struct DNode
{
Elemtype data;
struct DNode *next, *prior;
} DNode, *DLinkList;
DLinkList HeadInsert(DNode *L, int n)
{
DNode *s;
int i;
L = (DLinkList)malloc(sizeof(DNode));
L->data = NULL;
L->next = L;
L->prior = L;
for (i = 0; i < n; i++)
{
if (L->next == L)
{
s = (DNode *)malloc(sizeof(DNode));
scanf("%d", &s->data);
s->next = L->next;
L->next = s;
s->prior = L;
L->prior = s;
}
else
{
s = (DNode *)malloc(sizeof(DNode));
scanf("%d", &s->data);
s->next = L->next;
L->next = s;
L->next->prior = s;
s->prior = L;
}
}
printf("头插法建立双链表成功\n");
return L;
}
DLinkList TailInsert(DLinkList L, int n)
{
int i;
L = (DLinkList)malloc(sizeof(DNode));
L->data = NULL;
L->next = L;
L->prior = L;
DNode *s, *r;
for (i = 0; i < n; i++)
{
if(L->next == L){
s = (DNode *)malloc(sizeof(DNode));
scanf("%d", &s->data);
L->next = s;
L->prior = s;
s->prior = L;
s->next = L;
r = L->next;
}
else{
s = (DNode *)malloc(sizeof(DNode));
scanf("%d", &s->data);
s->next = r->next;
r->next = s;
s->prior = r;
L->prior = s;
r = s;
}
}
printf("尾插法建立双链表成功\n");
return L;
}
Status Length(DLinkList L)
{
DNode *s;
s = L->next;
int i = 0;
if (s == NULL)
{
printf("空表\n");
return error;
}
else
{
while (s->data != NULL)
{
i++;
s = s->next;
}
return i;
}
return error;
}
Status print(DLinkList L)
{
int n;
DNode *s = L->next;
while (s->data != NULL)
{
printf("%d ", s->data);
s = s->next;
}
printf("\n");
return ok;
}
int main()
{
int n;
DLinkList L;
L = TailInsert(L,5);
print(L);
n = Length(L);
printf("表长为:%d", n);
return 0;
}