本题要求实现带头结点的循环单链表的创建和单链表的区间删除。L是一个带头结点的循环单链表,函数ListCreate_CL用于创建一个循环单链表,函数ListDelete_CL用于删除取值大于min小于max的链表元素,用c加加实现
时间: 2024-10-08 07:23:17 浏览: 80
在C语言中,我们首先需要定义链表节点结构体,并实现循环链表的基本操作。下面是一个简单的示例,包含了创建循环链表`ListCreate_CL`和删除指定区间的元素`ListDelete_CL`的实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建循环单链表
Node* ListCreate_CL(int n) {
if (n <= 0) return NULL;
Node* head = (Node*)malloc(sizeof(Node)); // 头节点
head->data = 0; // 初始化头节点的数据
head->next = head; // 设置头节点指向自身形成循环
Node* tail = head; // 尾指针
for (int i = 1; i < n; ++i) { // 创建其他节点并链接到尾部
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = i;
newNode->next = tail->next;
tail->next = newNode;
tail = newNode;
}
return head;
}
// 删除指定区间的元素
void ListDelete_CL(Node* head, int min, int max) {
if (!head) return; // 如果链表为空则直接返回
Node* current = head;
while (true) {
if (current->data >= min && current->data <= max) {
Node* temp = current->next;
free(current); // 释放当前节点内存
current = temp;
// 检查是否已经回到头节点,如果是,则链表结束
if (current == head && current->next == head) break;
} else {
current = current->next;
// 循环链表判断,如果到达头节点并且下一个节点还是头节点,说明还在循环范围内
if (current == head && current->next == head) break;
}
}
}
// 打印链表
void PrintList(Node* head) {
Node* temp = head;
while (temp != head->next) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("%d\n", temp->data); // 输出循环部分
}
int main() {
Node* list = ListCreate_CL(10);
if (list) {
PrintList(list);
ListDelete_CL(list, 3, 7);
PrintList(list);
}
return 0;
}
```
阅读全文
相关推荐


















