用c语言写代码,分步实行 1.实现单循环链表的初始化、求数据元素个数、插入、删除、取数据元素等操作; 2.用插入法建立带头结点的单循环链表;3.设计测试主函数验证所设计单循环列表的正确性
时间: 2024-12-06 18:20:27 浏览: 5
C语言数据结构之双向循环链表的实例
首先,让我们逐步创建一个简单的单循环链表(singly linked list with circular structure)的C语言实现:
1. **初始化单循环链表结构**:
```c
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; // 设置头节点的数据
head->next = head; // 设置链表循环链接
return head;
}
```
2. **计算链表数据元素个数**:
```c
int countNodes(Node* head) {
int count = 0;
Node* temp = head;
do {
count++;
temp = temp->next;
} while (temp != head);
return count;
}
```
3. **插入数据到链表**:
```c
void insertNode(Node** head, int newData, int position) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = newData;
newNode->next = *head;
Node* current = *head;
for (int i = 0; i < position - 1 && current != *head; ++i) {
current = current->next;
}
if (current == *head) {
newNode->next = newNode;
} else {
newNode->next = current->next;
current->next = newNode;
}
}
```
4. **删除链表数据**:
```c
void deleteNode(Node** head, int data) {
if (*head == NULL) return;
Node* temp = *head;
Node* prev = NULL;
while (temp->data != data && temp->next != *head) {
prev = temp;
temp = temp->next;
}
if (temp->data == data) {
if (prev == NULL) { // 删除头节点
*head = temp->next;
} else {
prev->next = temp->next;
}
free(temp); // 释放内存
}
}
```
5. **获取并显示链表数据**:
```c
void displayList(Node* head) {
if (head == NULL) {
printf("List is empty.\n");
} else {
Node* temp = head;
printf("Circular linked list elements: ");
do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != head);
printf("\n");
}
}
```
6. **测试主函数**:
```c
int main() {
Node* myList = createList();
// 插入、删除和显示数据操作...
displayList(myList);
// 清理内存
deleteList(myList);
return 0;
}
// 辅助函数:删除整个链表
void deleteList(Node** head) {
Node* temp;
while ((temp = *head)) {
Node* nextTemp = temp->next;
free(temp);
*head = nextTemp;
}
}
```
阅读全文