【数据结构】循环单链表的实现(C语言)

 循环单链表应掌握以下基本操作:

1、建立一个空的循环单链表。

2、获得循环单链表的最后一个结点的位置。

3、输出循环单链表中各结点的值。

4、在循环单链表中查找值为x的结点。

5、在循环单链表中第i个结点后插入值为x的新结点。

6、在循环单链表中删除值为x 的结点。

以下是头文件:(可以有选择的看,有很多算法)

#ifndef CIRCLE_HEAD_LINK_H_INCLUDED
#define CIRCLE_HEAD_LINK_H_INCLUDED
#include <stdio.h> 
#include <stdlib.h>
typedef int datatype;
typedef struct circle_link
{
	datatype info;
	struct circle_link *next;
}N;
	
/*创建一个空链表*/
N *init()
{
	return NULL;
} 
	
/*创建一个循环单链表*/
N *creat(N *head)
{
	printf("以输入-1为结束\n"); 
	int x;
	N *p,*q,*h=head;
	scanf("%d",&x);
	while(x!=-1)
	{
		p=(N*)malloc(sizeof(N));
		p->info=x;
		p->next=NULL; 
		if(!h)
		{	
			q=p;
			h=p;
		}
		else
		{
			q->next=p;
			q=p;
		}
		scanf("%d",&x);
	}
	p->next=h;
	printf("\n创建完成\n"); 
	return h;
} 

/*打印循环单链表*/
void displ
  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
循环单链表是链表的一种特殊形式,它的特点是链表中的最后一个节点的指针指向第一个节点,形成一个闭合的环。在C语言中,操作循环单链表通常涉及创建、插入、删除和遍历等基本操作。 以下是一些基本操作的C语言实现概览: 1. **创建循环链表**: - 定义节点结构体,包含数据域和指向下一个节点的指针(如果是在头结点的最后一个节点,指针会指向自身)。 - 创建链表时,可以初始化一个头节点,然后递归地添加新节点到链尾。 ```c struct Node { int data; struct Node* next; }; // 创建循环链表 void createCircularList(struct Node** head, int size, ...) { ... } ``` 2. **插入节点**: - 可以在链表的头部、尾部或指定位置插入节点。 - 在头部插入,更新头节点的next;在尾部插入,找到当前尾节点,然后更新其next指向新节点,并将新节点next指向头节点。 ```c void insertNode(struct Node** head, int data, insertionPosition) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = data; newNode->next = (insertionPosition == 1) ? head : (*(head)->next); // 如果在尾部插入,更新尾节点和头节点的next指针 if (insertionPosition == 0) { (*head)->next = newNode; } } ``` 3. **删除节点**: - 删除某个节点时,需要找到前一个节点,然后更新其next指针跳过要删除的节点。 - 在循环链表中删除特定位置的节点需要特别处理头节点的情况。 ```c void deleteNode(struct Node** head, int position) { if (position == 1) { // 删除头节点 struct Node* temp = head->next; *head = temp; free(head); } else { struct Node* current = *head, *previous = NULL; for (int i = 1; i < position && current != NULL; ++i) { previous = current; current = current->next; } if (current == NULL) return; // 未找到节点 previous->next = current->next; } } ``` 4. **遍历循环链表**: - 使用while循环,每次迭代都更新当前节点指向下一个节点,直到遇到第一个节点。 ```c void printList(struct Node* head) { struct Node* temp = head; do { printf("%d ", temp->data); temp = temp->next; } while (temp != head); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值