双向链表双向冒泡排序用c语言写
时间: 2023-12-22 15:29:11 浏览: 89
以下是用C语言实现双向链表双向冒泡排序的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 双向链表节点结构体
struct Node {
int data;
struct Node* prev;
struct Node* next;
};
// 在链表末尾插入节点
void append(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;
new_node->data = new_data;
new_node->next = NULL;
if (*head_ref == NULL) {
new_node->prev = NULL;
*head_ref = new_node;
return;
}
while (last->next != NULL) {
last = last->next;
}
last->next = new_node;
new_node->prev = last;
}
// 交换两个节点的数据
void swap(struct Node* a, struct Node* b) {
int temp = a->data;
a->data = b->data;
b->data = temp;
}
// 双向冒泡排序
void bubbleSort(struct Node* head) {
int swapped;
struct Node* ptr1;
struct Node* lptr = NULL;
if (head == NULL) {
return;
}
do {
swapped = 0;
ptr1 = head;
while (ptr1->next != lptr) {
if (ptr1->data > ptr1->next->data) {
swap(ptr1, ptr1->next);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
} while (swapped);
}
// 打印链表
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data); node = node->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
// 在链表末尾插入节点
append(&head, 6);
append(&head, 3);
append(&head, 8);
append(&head, 2);
append(&head, 1);
printf("原始链表:\n");
printList(head);
// 双向冒泡排序
bubbleSort(head);
printf("排序后的链表:\n");
printList(head);
return 0;
}
```
阅读全文