c++建立一个有序的单链表。单链表中各结点的值和结点个数等自定。要求将建立好的有序单链表遍历输出。
时间: 2024-10-10 18:10:59 浏览: 45
在C++中,我们可以创建一个结构体来表示链表节点,包含数据和指向下一个节点的指针。为了实现一个有序单链表,我们需要定义一个比较函数,用于确定新插入的节点应该插入到当前已排序部分的何处。下面是一个简单的示例:
```cpp
#include <iostream>
// 定义链表节点结构
struct ListNode {
int val; // 节点值
ListNode* next; // 指向下一个节点的指针
};
// 比较函数,用于判断新节点的位置
bool compare(const ListNode* a, const ListNode* b) {
return a->val < b->val;
}
// 插入新节点到已排序链表中
ListNode* insertSorted(ListNode*& head, int val) {
if (head == nullptr || head->val >= val) {
ListNode* newNode = new ListNode{val, nullptr};
newNode->next = head;
head = newNode;
} else {
ListNode* curr = head;
while (curr->next && curr->next->val < val) {
curr = curr->next;
}
ListNode* newNode = new ListNode{val, nullptr};
newNode->next = curr->next;
curr->next = newNode;
}
return head;
}
// 遍历并打印链表
void printList(ListNode* head) {
ListNode* curr = head;
while (curr != nullptr) {
std::cout << curr->val << " ";
curr = curr->next;
}
std::cout << "\n";
}
int main() {
// 初始化链表为空
ListNode* head = nullptr;
// 添加一些已排序的元素
head = insertSorted(head, 5);
insertSorted(head, 2);
insertSorted(head, 7);
insertSorted(head, 1);
// 打印链表
printList(head); // 输出: 1 2 5 7
return 0;
}
```
在这个例子中,我们首先创建了一个空的链表`head`,然后通过`insertSorted`函数添加已排序的整数值。最后,`printList`函数遍历并打印链表的内容。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)