C语言 循环单链表的基本操作与实现
原理
循环链表于单链表的区别在于,表中最后一个节点不是指向NULL,而是改为指向头节点
,从而形成一个环如图
再循环单链表中,表尾节点 d 的Next指向L,所以表中没有NULL的节点,因此循环单链表判空条件不是头节点的指针是否为空,而是头节点是否等于头节点
.
实现
结构体
typedef struct SqNode
{
int data;
struct SqNode* Next;
}SqNode,*Sqlist;
初始化
Sqlist Initlist(Sqlist L)
{
L = (Sqlist)malloc(sizeof(SqNode));
if (!L)
return NULL;
L->Next = L;
return L;
}
创建链表
Sqlist CreateList(Sqlist L)
{
Sqlist s;
Sqlist r;
int Value;
s = L->Next;
printf("请输入您要创建的链表,输入999结束创建\n");
scanf_s("%d", &Value);
getchar();
while (Value!=999)
{
r = (Sqlist)malloc(sizeof(SqNode));
if (!r)
{
printf("内存分配失败,结束创建\n");
return L;
}
r->data = Value;
r->Next = s->Next;
s->Next = r;
s = r;
scanf_s("%d", &Value);
getchar();
}
return L;
}
获取链表长度
int LengthList(Sqlist L)
{
Sqlist s;
s = L->Next;
int Length = 0;
while (s != L)
{
s = s->Next;
Length++;
}
return Length;
}
根据节点位置删除节点
Sqlist DeleteList(Sqlist L, int Locate)
{
Sqlist s=L;
Sqlist q;
int Length = 0;
int i = 0;
Length = LengthList(L);
if (Locate > Length || Locate < 0)
{
printf("你输入的位置超出范围\n");
return NULL;
}
while (i<Locate-1 && s->Next!=L)
{
i++;
s = s->Next;
}
q=s->Next;
s->Next = s->Next->Next;
return q;
}
根据节点的位置插入数据
Sqlist InsertList(Sqlist L, int Locate)
{
Sqlist s;
Sqlist r;
int i=0;
int Value;
int Length = LengthList(L);
s = L;
if (Locate > Length || Locate < 0)
{
printf("您输入的位置超出有效范围\n");
return NULL;
}
while (i<Locate-1 &&s->Next!=L)
{
s=s->Next;
i++;
}
r = (Sqlist)malloc(sizeof(SqNode));
if (!r)
{
printf("申请空间失败\n");
return NULL;
}
s;
printf("请输入您需要插入的数据\n");
scanf_s("%d", &Value);
getchar();
r->data = Value;
r->Next = s->Next;
s->Next = r;
return L;
}
打印链表
void PrintfList(Sqlist L)
{
Sqlist s;
s = L->Next;
while (s!=L)
{
printf("%d\t", s->data);
s = s->Next;
}
printf("\n");
}