用C语言写一个循环链表
时间: 2023-12-29 20:48:13 浏览: 66
好的,我会为您提供C语言的循环链表代码示例。
首先,我们需要定义一个链表节点的结构体,如下所示:
```
typedef struct node {
int data;
struct node *next;
} Node;
```
其中,`data` 用来存储节点的数据,`next` 则指向下一个节点。
接下来,我们需要定义循环链表,并实现以下操作:
1. 初始化链表
```
void initList(Node **head) {
*head = NULL;
}
```
2. 在链表末尾添加节点
```
void append(Node **head, int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
if (*head == NULL) {
newNode->next = newNode;
*head = newNode;
} else {
newNode->next = (*head)->next;
(*head)->next = newNode;
*head = newNode;
}
}
```
3. 删除指定位置的节点
```
void delete(Node **head, int position) {
if (*head == NULL) {
return;
}
Node *current = *head;
Node *prev = NULL;
int i = 0;
while (i != position) {
prev = current;
current = current->next;
i++;
if (current == *head) {
return; // 到达链表末尾,没有找到指定位置的节点
}
}
if (current == *head) {
*head = prev;
}
prev->next = current->next;
free(current);
}
```
4. 打印链表中每个节点的数据
```
void printList(Node *head) {
if (head == NULL) {
return;
}
Node *current = head->next;
do {
printf("%d ", current->data);
current = current->next;
} while (current != head);
}
```
使用这些操作,我们可以轻松地创建、修改和打印循环链表。完整的示例代码如下:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
void initList(Node **head) {
*head = NULL;
}
void append(Node **head, int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
if (*head == NULL) {
newNode->next = newNode;
*head = newNode;
} else {
newNode->next = (*head)->next;
(*head)->next = newNode;
*head = newNode;
}
}
void delete(Node **head, int position) {
if (*head == NULL) {
return;
}
Node *current = *head;
Node *prev = NULL;
int i = 0;
while (i != position) {
prev = current;
current = current->next;
i++;
if (current == *head) {
return;
}
}
if (current == *head) {
*head = prev;
}
prev->next = current->next;
free(current);
}
void printList(Node *head) {
if (head == NULL) {
return;
}
Node *current = head->next;
do {
printf("%d ", current->data);
current = current->next;
} while (current != head);
}
int main() {
Node *head;
initList(&head);
append(&head, 1);
append(&head, 2);
append(&head, 3);
append(&head, 4);
printList(head);
delete(&head, 2);
printList(head);
return 0;
}
```
阅读全文