用c语言写一段完整的代码 用插入法建立带头结点的单循环链表,实现单循环链表的初始化、求数据元素个数、插入、删除、取数据元素等操作。
时间: 2024-10-08 11:13:11 浏览: 30
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 初始化链表
Node* createList() {
Node* head = (Node*)malloc(sizeof(Node));
if (!head) {
printf("Memory allocation failed.\n");
return NULL;
}
head->data = 0; // 默认头节点值为0
head->next = head; // 链表形成循环
return head;
}
// 求链表元素个数
int size(Node* head) {
int count = 0;
Node* temp = head;
while (temp != head->next) {
count++;
temp = temp->next;
}
return count + 1; // 包含头节点
}
// 插入元素到链表
void insert(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = (*head)->next;
(*head)->next = newNode; // 新节点连接到尾部并形成循环
}
// 删除指定位置的元素
void delete(Node** head, int index) {
if (index <= 0 || !(*head)) {
printf("Invalid index or empty list.\n");
return;
}
Node* current = *head;
Node* previous = NULL;
for (int i = 1; i < index && current != head->next; ++i) {
previous = current;
current = current->next;
}
if (current == head->next) { // 如果索引越界,不做处理
printf("Element not found.\n");
} else {
if (previous) {
previous->next = current->next;
} else {
*head = current->next; // 如果要删除的是头节点,更新头指针
}
free(current);
}
}
// 取数据元素
int getData(Node* head, int index) {
if (index <= 0 || !head || head->next == head) {
printf("Invalid index or empty list.\n");
return -1; // 返回无效数据
}
Node* current = head;
for (int i = 0; i < index; ++i) {
if (current == head->next) {
printf("Element not found.\n");
return -1;
}
current = current->next;
}
return current->data;
}
int main() {
Node* list = createList();
// 执行其他操作示例
insert(&list, 5);
printf("List size after insertion: %d\n", size(list));
int removedData = getData(list, 1);
if (removedData != -1) {
delete(&list, 1); // 删除第1个元素
printf("After deletion: Size is %d and data at position 1 is %d\n", size(list), removedData);
}
return 0;
}
```
阅读全文