循环链表简介:
循环链表是一种特殊的链表数据结构,与单向链表或双向链表相比,循环链表的最后一个节点的下一个节点指向第一个节点,从而形成一个环形结构。因此,循环链表可以在最后一个节点后继续添加节点,并且可以像单向链表或双向链表一样遍历、查找和删除节点。循环链表通常有一个头指针和一个尾指针,它们指向第一个节点和最后一个节点,以便在添加或删除节点时快速定位。
循环链表可以用于解决某些问题,例如模拟一个环形队列,或者用于实现循环播放的音乐列表等。循环链表的优点在于它具有链表的灵活性,同时可以避免在添加或删除节点时需要遍历整个链表的缺点。
以下是一个循环链表:
/*
This shows the coding basics of circular-linked-list in C programming.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
struct node
{
int data;
int key;
struct node *next;
};
struct node *head = NULL;
struct node *tail = NULL;
struct node *current = NULL;
bool isEmpty()
{
return head == NULL;
}
int length()
{
int length = 0;
//if list is empty
if(head == NULL)
{
return 0;
}
current = head->next;
// here different to single linked list
while(current != head)
{
length++;
current = current->next;
}
return length;
}
//insert link at the first location
void insertFirst(int key, int data)
{
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
// attention here, difference
if (isEmpty())
{
head = link;
head->next = head;
tail = head;
}
else
{
//point it to old first node
link->next = head;
//point first to new first node
head = link;
//update tail node
tail->next = head;
}
//printf("%p,%d,%d,%p\n",link,link->data,link->key,link->next);
//printf("current head: %p\n",head);
//printf("current tail->next: %p\n",tail->next);
}
//delete first item
struct node *deleteFirst()
{
//save reference