【c语言】循环链表(适合初学者)

循环链表简介:

循环链表是一种特殊的链表数据结构,与单向链表或双向链表相比,循环链表的最后一个节点的下一个节点指向第一个节点,从而形成一个环形结构。因此,循环链表可以在最后一个节点后继续添加节点,并且可以像单向链表或双向链表一样遍历、查找和删除节点。循环链表通常有一个头指针和一个尾指针,它们指向第一个节点和最后一个节点,以便在添加或删除节点时快速定位。

循环链表可以用于解决某些问题,例如模拟一个环形队列,或者用于实现循环播放的音乐列表等。循环链表的优点在于它具有链表的灵活性,同时可以避免在添加或删除节点时需要遍历整个链表的缺点。

以下是一个循环链表:

/*
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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值