建立单向链表整数从大到小排序c++
时间: 2023-08-03 22:17:21 浏览: 59
以下是建立单向链表并按整数从大到小排序的 C++ 代码示例:
```c++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* insertNode(ListNode* head, int val) {
ListNode* newNode = new ListNode(val);
if (head == NULL) {
return newNode;
}
if (val > head->val) {
newNode->next = head;
return newNode;
}
ListNode* cur = head;
while (cur->next != NULL && cur->next->val > val) {
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
return head;
}
ListNode* sortList(ListNode* head) {
ListNode* newHead = NULL;
ListNode* cur = head;
while (cur != NULL) {
ListNode* next = cur->next;
newHead = insertNode(newHead, cur->val);
cur = next;
}
return newHead;
}
void printList(ListNode* head) {
while (head != NULL) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int main() {
ListNode* head = NULL;
head = insertNode(head, 3);
head = insertNode(head, 1);
head = insertNode(head, 5);
head = insertNode(head, 2);
printList(head);
head = sortList(head);
printList(head);
return 0;
}
```
在此示例中,我们定义了一个 `ListNode` 结构体来表示链表节点,包含一个整数值 `val` 和一个指向下一个节点的指针 `next`。`insertNode` 函数用于将一个新节点插入到链表中,按整数从大到小排序。`sortList` 函数遍历原链表,将每个节点插入到新链表中,最终返回新链表的头节点。`printList` 函数用于打印链表中的所有节点值。
在 `main` 函数中,我们创建一个空链表,然后依次插入节点 3、1、5、2,打印原链表并排序后再次打印链表。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)