单向循环链表
单向循环链表是在单向链表的基础上,将尾结点的指针指向首元结点。
1、单向循环链表的创建
Status initList(LinkList *L,ElemType data){
*L = (LinkList)malloc(sizeof(Node));
if (*L==NULL) return ERROR;
(*L)->data = data;
(*L)->next = (*L);
return OK;
}
2、单向循环链表插入数据
Status insertList(LinkList *L, int i, ElemType data){
if (*L == NULL) return ERROR;
LinkList temp = (LinkList)malloc(sizeof(Node));
if (temp == NULL) return ERROR;
temp->data = data;
LinkList target;
if (i == 1) {
for (target = *L; target->next != *L; target = target->next);
target->next = temp;
temp->next = *L;
*L = temp;
}else{
int j;
for (j = 1, target = *L; target->next != *L && j<i-1; j++,target = target->next);
temp->next = target->next;
target->next = temp;
}
return OK;
}
3、单向循环链表删除元素
Status deleteList(LinkList *L, int i){
if (*L == NULL) return ERROR;
if ((*L)->next == *L) {
*L = NULL;
free(*L);
return OK;
}
LinkList temp, target;
if (i == 1) {
temp = *L;
for (target = *L; target->next != *L; target = target->next);
target->next = temp->next;
*L = target->next;
free(temp);
}else{
int j;
for (j = 1, target = *L; target->next != *L && j<i-1; j++,target = target->next);
if (target->next == *L) {
return ERROR;
}
temp = target->next;
target->next = temp->next;
free(temp);
}
return OK;
}
4、单向循环链表查询值
int searchValue(LinkList L, int value){
LinkList temp = L;
int i = 1;
while (temp->next != L && temp->data != value) {
i++;
temp = temp->next;
}
if (temp->next == L && temp->data != value) {
return -1;
}
return i;
}
5、遍历单向循环链表
void display(LinkList L){
if (L==NULL) {
printf("打印的链表为空!\n");
return;
}else{
printf("链表数据为:");
LinkList temp = L;
do{
printf("%5d",temp->data);
temp = temp->next;
}while (temp != L);
printf("\n");
}
}