用c语言写环形链表。实现链表的删除
时间: 2024-03-13 08:23:02 浏览: 73
以下是用C语言实现环形链表的基本代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义节点结构体
typedef struct node {
int data;
struct node *next;
} Node;
// 创建新节点
Node *new_node(int data) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
return node;
}
// 添加节点到链表末尾
void add_node(Node **head, int data) {
Node *node = new_node(data);
if (*head == NULL) {
*head = node;
(*head)->next = *head;
} else {
Node *curr = *head;
while (curr->next != *head) {
curr = curr->next;
}
curr->next = node;
node->next = *head;
}
}
// 打印链表
void print_list(Node *head) {
if (head == NULL) {
printf("List is empty.\n");
} else {
Node *curr = head;
do {
printf("%d ", curr->data);
curr = curr->next;
} while (curr != head);
printf("\n");
}
}
// 删除节点
void delete_node(Node **head, int data) {
if (*head == NULL) {
printf("List is empty.\n");
return;
}
Node *curr = *head;
Node *prev = NULL;
while (curr->data != data) {
prev = curr;
curr = curr->next;
if (curr == *head) {
printf("Node not found.\n");
return;
}
}
if (curr == *head && curr->next == *head) {
*head = NULL;
} else if (curr == *head) {
Node *last = *head;
while (last->next != *head) {
last = last->next;
}
*head = (*head)->next;
last->next = *head;
} else {
prev->next = curr->next;
}
free(curr);
}
int main() {
Node *head = NULL;
add_node(&head, 1);
add_node(&head, 2);
add_node(&head, 3);
add_node(&head, 4);
add_node(&head, 5);
print_list(head);
delete_node(&head, 3);
print_list(head);
delete_node(&head, 1);
print_list(head);
delete_node(&head, 5);
print_list(head);
return 0;
}
```
在这个代码中,我们通过定义一个指向自身的头节点来实现环形链表。添加节点时,我们遍历链表找到最后一个节点,然后将新节点添加到最后一个节点的后面,并将其指向头节点。删除节点时,我们遍历链表找到要删除的节点,并将其从链表中移除,然后释放内存。需要注意的是,如果要删除的是头节点,我们需要特殊处理。如果链表只有一个节点,我们将头节点设为NULL。
阅读全文