用c语言写一段代码 1. 实现单循环链表的初始化、求数据元素个数、插入、删除、取数据元素等操作; 2. 用插入法建立带头结点的单循环链表;
时间: 2024-10-08 19:11:09 浏览: 35
```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; // 将头结点的next指向自身形成循环链表
return head;
}
// 求链表元素个数
int getLength(Node* head) {
int count = 1;
Node* temp = head->next;
while (temp != head) {
++count;
temp = temp->next;
}
return count;
}
// 插入元素
void insert(int value, Node** head_ref) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = value;
newNode->next = (*head_ref)->next;
(*head_ref)->next = newNode;
newNode->next->next = *head_ref; // 维持循环链表结构
}
// 删除元素
void deleteElement(Node** head_ref, int value) {
if (*head_ref == NULL) {
printf("List is empty.\n");
return;
}
Node* temp = *head_ref, *prev = NULL;
while (temp != NULL && temp->data != value) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
printf("Value not found in the list.\n");
return;
}
if (prev == NULL) { // 如果待删除的是头结点
*head_ref = temp->next;
free(temp);
} else {
prev->next = temp->next;
free(temp);
}
}
// 取数据元素
int getData(Node* head) {
if (head == NULL) {
printf("List is empty.\n");
return -1;
}
return head->data;
}
int main() {
Node* head = createList();
// 测试并展示功能
printf("Initial list length: %d\n", getLength(head));
insert(5, &head);
printf("After inserting 5: ");
printList(head); // 自定义函数用于打印链表
deleteElement(&head, 5);
printf("After deleting 5: ");
printList(head);
printf("Head node data: %d\n", getData(head));
return 0;
}
// 打印链表辅助函数
void printList(Node* head) {
Node* temp = head;
while (temp != head->next) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("%d\n", temp->data); // 输出最后一个元素
}
```
阅读全文