使用C语言实现双向循环链表的增删改查以及从大到小和从小到大的链表排序
时间: 2024-03-09 22:45:37 浏览: 22
好的,我会尽力回答您的问题。
首先,我们来看一下双向循环链表的定义:
```c
typedef struct node {
int data;
struct node *prev;
struct node *next;
} Node;
typedef struct list {
Node *head;
Node *tail;
int size;
} List;
```
其中,`Node` 表示链表中的一个节点,包含数据和两个指针,分别指向前一个节点和后一个节点。`List` 表示链表本身,包含头节点、尾节点和链表大小。
接下来,我们来实现双向循环链表的增删改查和排序。
1. 增加节点
```c
void addNode(List *list, int data) {
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = data;
if (list->size == 0) {
newNode->prev = newNode;
newNode->next = newNode;
list->head = newNode;
list->tail = newNode;
} else {
newNode->prev = list->tail;
newNode->next = list->head;
list->tail->next = newNode;
list->head->prev = newNode;
list->tail = newNode;
}
list->size++;
}
```
2. 删除节点
```c
void deleteNode(List *list, Node *node) {
if (list->size == 0) {
return;
}
if (list->size == 1) {
list->head = NULL;
list->tail = NULL;
} else {
node->prev->next = node->next;
node->next->prev = node->prev;
if (node == list->head) {
list->head = node->next;
} else if (node == list->tail) {
list->tail = node->prev;
}
}
free(node);
list->size--;
}
```
3. 修改节点
```c
void modifyNode(List *list, Node *node, int data) {
node->data = data;
}
```
4. 查找节点
```c
Node* findNode(List *list, int data) {
Node *current = list->head;
while (current != NULL) {
if (current->data == data) {
return current;
}
current = current->next;
if (current == list->head) {
break;
}
}
return NULL;
}
```
5. 从小到大排序
```c
void sortAscending(List *list) {
Node *current = list->head;
int temp;
do {
Node *ptr = current->next;
while (ptr != list->head) {
if (current->data > ptr->data) {
temp = current->data;
current->data = ptr->data;
ptr->data = temp;
}
ptr = ptr->next;
}
current = current->next;
} while (current != list->head);
}
```
6. 从大到小排序
```c
void sortDescending(List *list) {
Node *current = list->head;
int temp;
do {
Node *ptr = current->next;
while (ptr != list->head) {
if (current->data < ptr->data) {
temp = current->data;
current->data = ptr->data;
ptr->data = temp;
}
ptr = ptr->next;
}
current = current->next;
} while (current != list->head);
}
```
以上就是双向循环链表的增删改查和排序的实现。希望能够帮到您!