日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

链表排序

發布時間:2025/6/17 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 链表排序 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

https://leetcode.com/problems/insertion-sort-list/description/

1、歸并排序:

#include <bits/stdc++.h> #include "table.h" using namespace std; typedef long long int LL;struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {} };class Solution { public:ListNode* findMid(ListNode *head) {if (head == NULL || head->next == NULL) return head;ListNode *slow = head, *fast = head->next;while (fast && fast->next) {slow = slow->next;fast = fast->next->next;}ListNode *tmp = slow->next;slow->next = NULL;return tmp;}ListNode* merge(ListNode* one, ListNode* two) {ListNode *first = NULL;if (one->val < two->val) {first = one;one = one->next;} else {first = two;two = two->next;}ListNode *ans = first;while (one && two) {if (one->val < two->val) {first->next = one;one = one->next;} else {first->next = two;two = two->next;}first = first->next;}while (one) {first->next = one;one = one->next;first = first->next;}while (two) {first->next = two;two = two->next;first = first->next;}return ans;}ListNode* guibin(ListNode* head) {if (head == NULL || head->next == NULL) return head;if (head->next->next == NULL) {if (head->val > head->next->val) {swap(head->val, head->next->val);}return head;}ListNode* mid = findMid(head);ListNode* one = guibin(head);ListNode* two = guibin(mid);return merge(one, two);}ListNode* insertionSortList(ListNode* head) {return guibin(head);} };void work() {int a[] = {4, 1, 2, 3, 5, 8};int len = sizeof(a) / sizeof(a[0]);ListNode* first = new ListNode(a[0]);ListNode* tmp = first;for (int i = 1; i < len; ++i) {first->next = new ListNode(a[i]);first = first->next;}tmp = t.insertionSortList(tmp);while (tmp) {printf("%d\n", tmp->val);tmp = tmp->next;} }int main() {work();return 0; } View Code

?

轉載于:https://www.cnblogs.com/liuweimingcprogram/p/9649582.html

總結

以上是生活随笔為你收集整理的链表排序的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。