线性表之循环链表
普通单链表就像一条巷子走到底,而循环链表就像巷子末尾有个传送门,把你又带回巷子开始的地方。普通单链表最后一个节点指向空,循环链表的最后一个节点指向头结点。
数据集的表示和单链表一样
typedef struct list
{
int data;
struct list *next;
} List;
实现代码

#include<stdio.h>
#include<stdlib.h>
//数据集表示
typedef struct list
{
int data;
struct list *next;
} List;
//操作集表示
//初始化
List* initList()
{
List *head = ( List* ) malloc ( sizeof(List) );
if( head == NULL )
{
printf("创建失败!");
exit(0);
}
else
{
head->next = NULL;
return head;
}
}
//创建操作
int createList( List *L , int n )
{
if( 0 >= n )
{
return 0;
}
//rear尾指针
List *rear,*p;
//计数器
int i;
rear = L;
for( i = 0 ; i < n ; i++ )
{
p = initList();
scanf("%d",&p->data);
//指向新节点
rear->next = p;
p->next = L;
//尾指针移动
rear = p;
}
return 1;
}
//插入操作
int insertList( List *L , int pos , int e )
{
List *node = initList();
List *p = L;
int i;
if( L != NULL )
{
for( i = 1 ; i < pos ; i++ )
{
p = p->next;
}
//赋值
node->data = e;
//新节点指向下一个节点
node->next = p->next;
//指向新节点
p->next = node;
return 1;
}
return 0;
}
//遍历
void printList( List *L )
{
//头结点赋值给p
List *p = L->next;
/**
*这里的结束条件和单链表的遍历不一样
*/
while( p != L )
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
//删除操作
int deleteList( List *L )
{
if( L == NULL )
{
printf("链表为空");
return 0;
}
List *temp = L;
List *p = L->next;
int del;
printf("请输入你要删除的元素:");
scanf("%d",&del);
while( p != L )
{
if( p->data == del )
{
temp->next = p->next;
free(p);
return 1;
}
temp = temp->next;
p = p->next;
}
return 0;
}
int main()
{
List *L = initList();
L->next = L;
printf("请输入你要链表的元素:");
createList(L,5);
insertList(L,2,10);
printList(L);
deleteList(L);
printList(L);
return 0;
}
纸上得来终觉浅,绝知此事要躬行