用c语言写一段代码 1.实现单循环链表的初始化、求数据元素个数、插入、删除、取数据元素等操作; 2.用插入法建立带头结点的单循环链表;
时间: 2024-10-08 21:13:29 浏览: 35
首先,我们先定义单循环链表的数据结构和基本操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单循环链表节点结构
typedef struct Node {
int data; // 节点数据
struct Node* next; // 指向下一个节点的指针
struct Node* prev; // 指向前一个节点的指针(单循环链表特有的)
} Node;
// 创建一个新的节点
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = newNode; // 将新节点链接到自身作为单循环链表的起点
newNode->prev = newNode; // 同样,链接到自身作为单循环链表的终点
return newNode;
}
// 插入节点
void insertNode(Node** head, int value, int position) {
Node* newNode = createNode(value);
if (*head == NULL) { // 如果链表为空,直接作为首尾
*head = newNode;
(*head)->prev = *head;
} else if (position == 1) { // 插入在第一个位置(相当于头部)
newNode->next = *head;
newNode->prev = *head->prev;
*head->prev->next = newNode;
*head->prev = newNode;
} else { // 插入在其他位置
Node* current = *head;
for (int i = 1; i < position - 1; ++i) {
current = current->next;
}
newNode->next = current->next;
newNode->prev = current;
current->next->prev = newNode;
current->next = newNode;
}
}
// 删除节点
void deleteNode(Node** head, int position) {
if (*head == NULL) return;
if (position == 1) { // 删除第一个节点(头部)
Node* temp = *head;
*head = *head->next;
free(temp);
if (*head != NULL) (*head)->prev = *head; // 更新头节点的前一个指针
} else {
Node* current = *head;
for (int i = 1; i < position - 1; ++i) {
current = current->next;
}
current->next->prev = current->prev;
current->prev->next = current->next;
}
}
// 显示链表内容(假设只有一个节点)
void displayList(Node* head) {
if (head == NULL) return;
printf("%d ", head->data);
while (head->next != head) {
head = head->next;
printf("%d ", head->data);
}
printf("\n");
}
// 求节点总数
size_t countNodes(Node* head) {
size_t count = 1;
Node* current = head;
while (current->next != current) {
current = current->next;
count++;
}
return count;
}
int main() {
Node* listHead = NULL;
// 初始化(如添加一些节点)
insertNode(&listHead, 1, 1);
insertNode(&listHead, 2, 2);
insertNode(&listHead, 3, 3);
printf("Initial list: ");
displayList(listHead);
// 示例操作
displayList(listHead); // 打印当前链表
deleteNode(&listHead, 2); // 删除第二个节点
printf("After deleting node 2: ");
displayList(listHead);
printf("Number of nodes: %zu\n", countNodes(listHead));
return 0;
}
```
阅读全文