C++链表bool排序
时间: 2024-06-16 22:06:01 浏览: 11
C++链表的排序可以使用不同的算法来实现,其中一种常的方法是使用冒泡排序或者插入排序。下面是使用冒泡排序对链表进行bool排序的示例代码:
```cpp
#include <iostream>
struct Node {
bool data;
Node* next;
};
void bubbleSort(Node* head) {
if (head == nullptr || head->next == nullptr) {
return;
}
bool swapped;
Node* ptr1;
Node* lptr = nullptr;
do {
swapped = false;
ptr1 = head;
while (ptr1->next != lptr) {
if (ptr1->data > ptr1->next->data) {
bool temp = ptr1->data;
ptr1->data = ptr1->next->data;
ptr1->next->data = temp;
swapped = true;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
} while (swapped);
}
void printList(Node* node) {
while (node != nullptr) {
std::cout << node->data << " ";
node = node->next;
}
std::cout << std::endl;
}
int main() {
Node* head = new Node();
Node* second = new Node();
Node* third = new Node();
head->data = true;
head->next = second;
second->data = false;
second->next = third;
third->data = true;
third->next = nullptr;
std::cout << "Before sorting: ";
printList(head);
bubbleSort(head);
std::cout << "After sorting: ";
printList(head);
return 0;
}
```
这段代码中,我们定义了一个简单的链表结构`Node`,其中包含一个bool类型的数据`data`和指向下一个节点的指针`next`。然后,我们使用冒泡排序算法对链表进行排序,最后打印排序后的链表。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)